1 //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This provides C++ code generation targeting the Itanium C++ ABI. The class 11 // in this file generates structures that follow the Itanium C++ ABI, which is 12 // documented at: 13 // http://www.codesourcery.com/public/cxx-abi/abi.html 14 // http://www.codesourcery.com/public/cxx-abi/abi-eh.html 15 // 16 // It also supports the closely-related ARM ABI, documented at: 17 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "CGCXXABI.h" 22 #include "CGRecordLayout.h" 23 #include "CGVTables.h" 24 #include "CodeGenFunction.h" 25 #include "CodeGenModule.h" 26 #include "clang/AST/Mangle.h" 27 #include "clang/AST/Type.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/Value.h" 31 32 using namespace clang; 33 using namespace CodeGen; 34 35 namespace { 36 class ItaniumCXXABI : public CodeGen::CGCXXABI { 37 protected: 38 bool UseARMMethodPtrABI; 39 bool UseARMGuardVarABI; 40 41 public: 42 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, 43 bool UseARMMethodPtrABI = false, 44 bool UseARMGuardVarABI = false) : 45 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI), 46 UseARMGuardVarABI(UseARMGuardVarABI) { } 47 48 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const { 49 // Structures with either a non-trivial destructor or a non-trivial 50 // copy constructor are always indirect. 51 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor(); 52 } 53 54 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const { 55 // Structures with either a non-trivial destructor or a non-trivial 56 // copy constructor are always indirect. 57 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) 58 return RAA_Indirect; 59 return RAA_Default; 60 } 61 62 bool isZeroInitializable(const MemberPointerType *MPT); 63 64 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT); 65 66 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 67 llvm::Value *&This, 68 llvm::Value *MemFnPtr, 69 const MemberPointerType *MPT); 70 71 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, 72 llvm::Value *Base, 73 llvm::Value *MemPtr, 74 const MemberPointerType *MPT); 75 76 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 77 const CastExpr *E, 78 llvm::Value *Src); 79 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 80 llvm::Constant *Src); 81 82 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT); 83 84 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD); 85 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 86 CharUnits offset); 87 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT); 88 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD, 89 CharUnits ThisAdjustment); 90 91 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 92 llvm::Value *L, 93 llvm::Value *R, 94 const MemberPointerType *MPT, 95 bool Inequality); 96 97 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 98 llvm::Value *Addr, 99 const MemberPointerType *MPT); 100 101 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, 102 llvm::Value *ptr, 103 QualType type); 104 105 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF, 106 llvm::Value *This, 107 const CXXRecordDecl *ClassDecl, 108 const CXXRecordDecl *BaseClassDecl); 109 110 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 111 CXXCtorType T, 112 CanQualType &ResTy, 113 SmallVectorImpl<CanQualType> &ArgTys); 114 115 void EmitCXXConstructors(const CXXConstructorDecl *D); 116 117 void BuildDestructorSignature(const CXXDestructorDecl *Dtor, 118 CXXDtorType T, 119 CanQualType &ResTy, 120 SmallVectorImpl<CanQualType> &ArgTys); 121 122 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 123 CXXDtorType DT) const { 124 // Itanium does not emit any destructor variant as an inline thunk. 125 // Delegating may occur as an optimization, but all variants are either 126 // emitted with external linkage or as linkonce if they are inline and used. 127 return false; 128 } 129 130 void EmitCXXDestructors(const CXXDestructorDecl *D); 131 132 void BuildInstanceFunctionParams(CodeGenFunction &CGF, 133 QualType &ResTy, 134 FunctionArgList &Params); 135 136 void EmitInstanceFunctionProlog(CodeGenFunction &CGF); 137 138 void EmitConstructorCall(CodeGenFunction &CGF, 139 const CXXConstructorDecl *D, CXXCtorType Type, 140 bool ForVirtualBase, bool Delegating, 141 llvm::Value *This, 142 CallExpr::const_arg_iterator ArgBeg, 143 CallExpr::const_arg_iterator ArgEnd); 144 145 void EmitVirtualDestructorCall(CodeGenFunction &CGF, 146 const CXXDestructorDecl *Dtor, 147 CXXDtorType DtorType, SourceLocation CallLoc, 148 llvm::Value *This); 149 150 void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage, 151 const CXXRecordDecl *RD); 152 153 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; } 154 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; } 155 156 CharUnits getArrayCookieSizeImpl(QualType elementType); 157 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 158 llvm::Value *NewPtr, 159 llvm::Value *NumElements, 160 const CXXNewExpr *expr, 161 QualType ElementType); 162 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 163 llvm::Value *allocPtr, 164 CharUnits cookieSize); 165 166 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 167 llvm::GlobalVariable *DeclPtr, bool PerformInit); 168 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 169 llvm::Constant *dtor, llvm::Constant *addr); 170 171 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD, 172 llvm::GlobalVariable *Var); 173 void EmitThreadLocalInitFuncs( 174 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls, 175 llvm::Function *InitFunc); 176 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF, 177 const DeclRefExpr *DRE); 178 179 bool NeedsVTTParameter(GlobalDecl GD); 180 }; 181 182 class ARMCXXABI : public ItaniumCXXABI { 183 public: 184 ARMCXXABI(CodeGen::CodeGenModule &CGM) : 185 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 186 /* UseARMGuardVarABI = */ true) {} 187 188 bool HasThisReturn(GlobalDecl GD) const { 189 return (isa<CXXConstructorDecl>(GD.getDecl()) || ( 190 isa<CXXDestructorDecl>(GD.getDecl()) && 191 GD.getDtorType() != Dtor_Deleting)); 192 } 193 194 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy); 195 196 CharUnits getArrayCookieSizeImpl(QualType elementType); 197 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 198 llvm::Value *NewPtr, 199 llvm::Value *NumElements, 200 const CXXNewExpr *expr, 201 QualType ElementType); 202 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr, 203 CharUnits cookieSize); 204 }; 205 } 206 207 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) { 208 switch (CGM.getTarget().getCXXABI().getKind()) { 209 // For IR-generation purposes, there's no significant difference 210 // between the ARM and iOS ABIs. 211 case TargetCXXABI::GenericARM: 212 case TargetCXXABI::iOS: 213 return new ARMCXXABI(CGM); 214 215 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't 216 // include the other 32-bit ARM oddities: constructor/destructor return values 217 // and array cookies. 218 case TargetCXXABI::GenericAArch64: 219 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 220 /* UseARMGuardVarABI = */ true); 221 222 case TargetCXXABI::GenericItanium: 223 if (CGM.getContext().getTargetInfo().getTriple().getArch() 224 == llvm::Triple::le32) { 225 // For PNaCl, use ARM-style method pointers so that PNaCl code 226 // does not assume anything about the alignment of function 227 // pointers. 228 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 229 /* UseARMGuardVarABI = */ false); 230 } 231 return new ItaniumCXXABI(CGM); 232 233 case TargetCXXABI::Microsoft: 234 llvm_unreachable("Microsoft ABI is not Itanium-based"); 235 } 236 llvm_unreachable("bad ABI kind"); 237 } 238 239 llvm::Type * 240 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 241 if (MPT->isMemberDataPointer()) 242 return CGM.PtrDiffTy; 243 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL); 244 } 245 246 /// In the Itanium and ARM ABIs, method pointers have the form: 247 /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr; 248 /// 249 /// In the Itanium ABI: 250 /// - method pointers are virtual if (memptr.ptr & 1) is nonzero 251 /// - the this-adjustment is (memptr.adj) 252 /// - the virtual offset is (memptr.ptr - 1) 253 /// 254 /// In the ARM ABI: 255 /// - method pointers are virtual if (memptr.adj & 1) is nonzero 256 /// - the this-adjustment is (memptr.adj >> 1) 257 /// - the virtual offset is (memptr.ptr) 258 /// ARM uses 'adj' for the virtual flag because Thumb functions 259 /// may be only single-byte aligned. 260 /// 261 /// If the member is virtual, the adjusted 'this' pointer points 262 /// to a vtable pointer from which the virtual offset is applied. 263 /// 264 /// If the member is non-virtual, memptr.ptr is the address of 265 /// the function to call. 266 llvm::Value * 267 ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 268 llvm::Value *&This, 269 llvm::Value *MemFnPtr, 270 const MemberPointerType *MPT) { 271 CGBuilderTy &Builder = CGF.Builder; 272 273 const FunctionProtoType *FPT = 274 MPT->getPointeeType()->getAs<FunctionProtoType>(); 275 const CXXRecordDecl *RD = 276 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 277 278 llvm::FunctionType *FTy = 279 CGM.getTypes().GetFunctionType( 280 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 281 282 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1); 283 284 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual"); 285 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual"); 286 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end"); 287 288 // Extract memptr.adj, which is in the second field. 289 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj"); 290 291 // Compute the true adjustment. 292 llvm::Value *Adj = RawAdj; 293 if (UseARMMethodPtrABI) 294 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted"); 295 296 // Apply the adjustment and cast back to the original struct type 297 // for consistency. 298 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 299 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj); 300 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 301 302 // Load the function pointer. 303 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr"); 304 305 // If the LSB in the function pointer is 1, the function pointer points to 306 // a virtual function. 307 llvm::Value *IsVirtual; 308 if (UseARMMethodPtrABI) 309 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1); 310 else 311 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1); 312 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual"); 313 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 314 315 // In the virtual path, the adjustment left 'This' pointing to the 316 // vtable of the correct base subobject. The "function pointer" is an 317 // offset within the vtable (+1 for the virtual flag on non-ARM). 318 CGF.EmitBlock(FnVirtual); 319 320 // Cast the adjusted this to a pointer to vtable pointer and load. 321 llvm::Type *VTableTy = Builder.getInt8PtrTy(); 322 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo()); 323 VTable = Builder.CreateLoad(VTable, "memptr.vtable"); 324 325 // Apply the offset. 326 llvm::Value *VTableOffset = FnAsInt; 327 if (!UseARMMethodPtrABI) 328 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1); 329 VTable = Builder.CreateGEP(VTable, VTableOffset); 330 331 // Load the virtual function to call. 332 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo()); 333 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn"); 334 CGF.EmitBranch(FnEnd); 335 336 // In the non-virtual path, the function pointer is actually a 337 // function pointer. 338 CGF.EmitBlock(FnNonVirtual); 339 llvm::Value *NonVirtualFn = 340 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn"); 341 342 // We're done. 343 CGF.EmitBlock(FnEnd); 344 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2); 345 Callee->addIncoming(VirtualFn, FnVirtual); 346 Callee->addIncoming(NonVirtualFn, FnNonVirtual); 347 return Callee; 348 } 349 350 /// Compute an l-value by applying the given pointer-to-member to a 351 /// base object. 352 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, 353 llvm::Value *Base, 354 llvm::Value *MemPtr, 355 const MemberPointerType *MPT) { 356 assert(MemPtr->getType() == CGM.PtrDiffTy); 357 358 CGBuilderTy &Builder = CGF.Builder; 359 360 unsigned AS = Base->getType()->getPointerAddressSpace(); 361 362 // Cast to char*. 363 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 364 365 // Apply the offset, which we assume is non-null. 366 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset"); 367 368 // Cast the address to the appropriate pointer type, adopting the 369 // address space of the base pointer. 370 llvm::Type *PType 371 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 372 return Builder.CreateBitCast(Addr, PType); 373 } 374 375 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer 376 /// conversion. 377 /// 378 /// Bitcast conversions are always a no-op under Itanium. 379 /// 380 /// Obligatory offset/adjustment diagram: 381 /// <-- offset --> <-- adjustment --> 382 /// |--------------------------|----------------------|--------------------| 383 /// ^Derived address point ^Base address point ^Member address point 384 /// 385 /// So when converting a base member pointer to a derived member pointer, 386 /// we add the offset to the adjustment because the address point has 387 /// decreased; and conversely, when converting a derived MP to a base MP 388 /// we subtract the offset from the adjustment because the address point 389 /// has increased. 390 /// 391 /// The standard forbids (at compile time) conversion to and from 392 /// virtual bases, which is why we don't have to consider them here. 393 /// 394 /// The standard forbids (at run time) casting a derived MP to a base 395 /// MP when the derived MP does not point to a member of the base. 396 /// This is why -1 is a reasonable choice for null data member 397 /// pointers. 398 llvm::Value * 399 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 400 const CastExpr *E, 401 llvm::Value *src) { 402 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 403 E->getCastKind() == CK_BaseToDerivedMemberPointer || 404 E->getCastKind() == CK_ReinterpretMemberPointer); 405 406 // Under Itanium, reinterprets don't require any additional processing. 407 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 408 409 // Use constant emission if we can. 410 if (isa<llvm::Constant>(src)) 411 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src)); 412 413 llvm::Constant *adj = getMemberPointerAdjustment(E); 414 if (!adj) return src; 415 416 CGBuilderTy &Builder = CGF.Builder; 417 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 418 419 const MemberPointerType *destTy = 420 E->getType()->castAs<MemberPointerType>(); 421 422 // For member data pointers, this is just a matter of adding the 423 // offset if the source is non-null. 424 if (destTy->isMemberDataPointer()) { 425 llvm::Value *dst; 426 if (isDerivedToBase) 427 dst = Builder.CreateNSWSub(src, adj, "adj"); 428 else 429 dst = Builder.CreateNSWAdd(src, adj, "adj"); 430 431 // Null check. 432 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType()); 433 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull"); 434 return Builder.CreateSelect(isNull, src, dst); 435 } 436 437 // The this-adjustment is left-shifted by 1 on ARM. 438 if (UseARMMethodPtrABI) { 439 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 440 offset <<= 1; 441 adj = llvm::ConstantInt::get(adj->getType(), offset); 442 } 443 444 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj"); 445 llvm::Value *dstAdj; 446 if (isDerivedToBase) 447 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj"); 448 else 449 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj"); 450 451 return Builder.CreateInsertValue(src, dstAdj, 1); 452 } 453 454 llvm::Constant * 455 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E, 456 llvm::Constant *src) { 457 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 458 E->getCastKind() == CK_BaseToDerivedMemberPointer || 459 E->getCastKind() == CK_ReinterpretMemberPointer); 460 461 // Under Itanium, reinterprets don't require any additional processing. 462 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 463 464 // If the adjustment is trivial, we don't need to do anything. 465 llvm::Constant *adj = getMemberPointerAdjustment(E); 466 if (!adj) return src; 467 468 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 469 470 const MemberPointerType *destTy = 471 E->getType()->castAs<MemberPointerType>(); 472 473 // For member data pointers, this is just a matter of adding the 474 // offset if the source is non-null. 475 if (destTy->isMemberDataPointer()) { 476 // null maps to null. 477 if (src->isAllOnesValue()) return src; 478 479 if (isDerivedToBase) 480 return llvm::ConstantExpr::getNSWSub(src, adj); 481 else 482 return llvm::ConstantExpr::getNSWAdd(src, adj); 483 } 484 485 // The this-adjustment is left-shifted by 1 on ARM. 486 if (UseARMMethodPtrABI) { 487 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 488 offset <<= 1; 489 adj = llvm::ConstantInt::get(adj->getType(), offset); 490 } 491 492 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1); 493 llvm::Constant *dstAdj; 494 if (isDerivedToBase) 495 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj); 496 else 497 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj); 498 499 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1); 500 } 501 502 llvm::Constant * 503 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 504 // Itanium C++ ABI 2.3: 505 // A NULL pointer is represented as -1. 506 if (MPT->isMemberDataPointer()) 507 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true); 508 509 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0); 510 llvm::Constant *Values[2] = { Zero, Zero }; 511 return llvm::ConstantStruct::getAnon(Values); 512 } 513 514 llvm::Constant * 515 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 516 CharUnits offset) { 517 // Itanium C++ ABI 2.3: 518 // A pointer to data member is an offset from the base address of 519 // the class object containing it, represented as a ptrdiff_t 520 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()); 521 } 522 523 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 524 return BuildMemberPointer(MD, CharUnits::Zero()); 525 } 526 527 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD, 528 CharUnits ThisAdjustment) { 529 assert(MD->isInstance() && "Member function must not be static!"); 530 MD = MD->getCanonicalDecl(); 531 532 CodeGenTypes &Types = CGM.getTypes(); 533 534 // Get the function pointer (or index if this is a virtual function). 535 llvm::Constant *MemPtr[2]; 536 if (MD->isVirtual()) { 537 uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD); 538 539 const ASTContext &Context = getContext(); 540 CharUnits PointerWidth = 541 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 542 uint64_t VTableOffset = (Index * PointerWidth.getQuantity()); 543 544 if (UseARMMethodPtrABI) { 545 // ARM C++ ABI 3.2.1: 546 // This ABI specifies that adj contains twice the this 547 // adjustment, plus 1 if the member function is virtual. The 548 // least significant bit of adj then makes exactly the same 549 // discrimination as the least significant bit of ptr does for 550 // Itanium. 551 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset); 552 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 553 2 * ThisAdjustment.getQuantity() + 1); 554 } else { 555 // Itanium C++ ABI 2.3: 556 // For a virtual function, [the pointer field] is 1 plus the 557 // virtual table offset (in bytes) of the function, 558 // represented as a ptrdiff_t. 559 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1); 560 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 561 ThisAdjustment.getQuantity()); 562 } 563 } else { 564 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 565 llvm::Type *Ty; 566 // Check whether the function has a computable LLVM signature. 567 if (Types.isFuncTypeConvertible(FPT)) { 568 // The function has a computable LLVM signature; use the correct type. 569 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 570 } else { 571 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 572 // function type is incomplete. 573 Ty = CGM.PtrDiffTy; 574 } 575 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty); 576 577 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy); 578 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 579 (UseARMMethodPtrABI ? 2 : 1) * 580 ThisAdjustment.getQuantity()); 581 } 582 583 return llvm::ConstantStruct::getAnon(MemPtr); 584 } 585 586 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP, 587 QualType MPType) { 588 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 589 const ValueDecl *MPD = MP.getMemberPointerDecl(); 590 if (!MPD) 591 return EmitNullMemberPointer(MPT); 592 593 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 594 595 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 596 return BuildMemberPointer(MD, ThisAdjustment); 597 598 CharUnits FieldOffset = 599 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 600 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 601 } 602 603 /// The comparison algorithm is pretty easy: the member pointers are 604 /// the same if they're either bitwise identical *or* both null. 605 /// 606 /// ARM is different here only because null-ness is more complicated. 607 llvm::Value * 608 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 609 llvm::Value *L, 610 llvm::Value *R, 611 const MemberPointerType *MPT, 612 bool Inequality) { 613 CGBuilderTy &Builder = CGF.Builder; 614 615 llvm::ICmpInst::Predicate Eq; 616 llvm::Instruction::BinaryOps And, Or; 617 if (Inequality) { 618 Eq = llvm::ICmpInst::ICMP_NE; 619 And = llvm::Instruction::Or; 620 Or = llvm::Instruction::And; 621 } else { 622 Eq = llvm::ICmpInst::ICMP_EQ; 623 And = llvm::Instruction::And; 624 Or = llvm::Instruction::Or; 625 } 626 627 // Member data pointers are easy because there's a unique null 628 // value, so it just comes down to bitwise equality. 629 if (MPT->isMemberDataPointer()) 630 return Builder.CreateICmp(Eq, L, R); 631 632 // For member function pointers, the tautologies are more complex. 633 // The Itanium tautology is: 634 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj)) 635 // The ARM tautology is: 636 // (L == R) <==> (L.ptr == R.ptr && 637 // (L.adj == R.adj || 638 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0))) 639 // The inequality tautologies have exactly the same structure, except 640 // applying De Morgan's laws. 641 642 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr"); 643 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr"); 644 645 // This condition tests whether L.ptr == R.ptr. This must always be 646 // true for equality to hold. 647 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr"); 648 649 // This condition, together with the assumption that L.ptr == R.ptr, 650 // tests whether the pointers are both null. ARM imposes an extra 651 // condition. 652 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType()); 653 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null"); 654 655 // This condition tests whether L.adj == R.adj. If this isn't 656 // true, the pointers are unequal unless they're both null. 657 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj"); 658 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj"); 659 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj"); 660 661 // Null member function pointers on ARM clear the low bit of Adj, 662 // so the zero condition has to check that neither low bit is set. 663 if (UseARMMethodPtrABI) { 664 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1); 665 666 // Compute (l.adj | r.adj) & 1 and test it against zero. 667 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj"); 668 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One); 669 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero, 670 "cmp.or.adj"); 671 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero); 672 } 673 674 // Tie together all our conditions. 675 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq); 676 Result = Builder.CreateBinOp(And, PtrEq, Result, 677 Inequality ? "memptr.ne" : "memptr.eq"); 678 return Result; 679 } 680 681 llvm::Value * 682 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 683 llvm::Value *MemPtr, 684 const MemberPointerType *MPT) { 685 CGBuilderTy &Builder = CGF.Builder; 686 687 /// For member data pointers, this is just a check against -1. 688 if (MPT->isMemberDataPointer()) { 689 assert(MemPtr->getType() == CGM.PtrDiffTy); 690 llvm::Value *NegativeOne = 691 llvm::Constant::getAllOnesValue(MemPtr->getType()); 692 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool"); 693 } 694 695 // In Itanium, a member function pointer is not null if 'ptr' is not null. 696 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr"); 697 698 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0); 699 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool"); 700 701 // On ARM, a member function pointer is also non-null if the low bit of 'adj' 702 // (the virtual bit) is set. 703 if (UseARMMethodPtrABI) { 704 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1); 705 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj"); 706 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit"); 707 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero, 708 "memptr.isvirtual"); 709 Result = Builder.CreateOr(Result, IsVirtual); 710 } 711 712 return Result; 713 } 714 715 /// The Itanium ABI requires non-zero initialization only for data 716 /// member pointers, for which '0' is a valid offset. 717 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 718 return MPT->getPointeeType()->isFunctionType(); 719 } 720 721 /// The Itanium ABI always places an offset to the complete object 722 /// at entry -2 in the vtable. 723 llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF, 724 llvm::Value *ptr, 725 QualType type) { 726 // Grab the vtable pointer as an intptr_t*. 727 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo()); 728 729 // Track back to entry -2 and pull out the offset there. 730 llvm::Value *offsetPtr = 731 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr"); 732 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr); 733 offset->setAlignment(CGF.PointerAlignInBytes); 734 735 // Apply the offset. 736 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy); 737 return CGF.Builder.CreateInBoundsGEP(ptr, offset); 738 } 739 740 llvm::Value * 741 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, 742 llvm::Value *This, 743 const CXXRecordDecl *ClassDecl, 744 const CXXRecordDecl *BaseClassDecl) { 745 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy); 746 CharUnits VBaseOffsetOffset = 747 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl); 748 749 llvm::Value *VBaseOffsetPtr = 750 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 751 "vbase.offset.ptr"); 752 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr, 753 CGM.PtrDiffTy->getPointerTo()); 754 755 llvm::Value *VBaseOffset = 756 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 757 758 return VBaseOffset; 759 } 760 761 /// The generic ABI passes 'this', plus a VTT if it's initializing a 762 /// base subobject. 763 void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor, 764 CXXCtorType Type, 765 CanQualType &ResTy, 766 SmallVectorImpl<CanQualType> &ArgTys) { 767 ASTContext &Context = getContext(); 768 769 // 'this' parameter is already there, as well as 'this' return if 770 // HasThisReturn(GlobalDecl(Ctor, Type)) is true 771 772 // Check if we need to add a VTT parameter (which has type void **). 773 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0) 774 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy)); 775 } 776 777 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 778 // Just make sure we're in sync with TargetCXXABI. 779 assert(CGM.getTarget().getCXXABI().hasConstructorVariants()); 780 781 // The constructor used for constructing this as a complete class; 782 // constucts the virtual bases, then calls the base constructor. 783 if (!D->getParent()->isAbstract()) { 784 // We don't need to emit the complete ctor if the class is abstract. 785 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 786 } 787 788 // The constructor used for constructing this as a base class; 789 // ignores virtual bases. 790 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base)); 791 } 792 793 /// The generic ABI passes 'this', plus a VTT if it's destroying a 794 /// base subobject. 795 void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 796 CXXDtorType Type, 797 CanQualType &ResTy, 798 SmallVectorImpl<CanQualType> &ArgTys) { 799 ASTContext &Context = getContext(); 800 801 // 'this' parameter is already there, as well as 'this' return if 802 // HasThisReturn(GlobalDecl(Dtor, Type)) is true 803 804 // Check if we need to add a VTT parameter (which has type void **). 805 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0) 806 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy)); 807 } 808 809 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 810 // The destructor in a virtual table is always a 'deleting' 811 // destructor, which calls the complete destructor and then uses the 812 // appropriate operator delete. 813 if (D->isVirtual()) 814 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting)); 815 816 // The destructor used for destructing this as a most-derived class; 817 // call the base destructor and then destructs any virtual bases. 818 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete)); 819 820 // The destructor used for destructing this as a base class; ignores 821 // virtual bases. 822 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 823 } 824 825 void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF, 826 QualType &ResTy, 827 FunctionArgList &Params) { 828 /// Create the 'this' variable. 829 BuildThisParam(CGF, Params); 830 831 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 832 assert(MD->isInstance()); 833 834 // Check if we need a VTT parameter as well. 835 if (NeedsVTTParameter(CGF.CurGD)) { 836 ASTContext &Context = getContext(); 837 838 // FIXME: avoid the fake decl 839 QualType T = Context.getPointerType(Context.VoidPtrTy); 840 ImplicitParamDecl *VTTDecl 841 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(), 842 &Context.Idents.get("vtt"), T); 843 Params.push_back(VTTDecl); 844 getVTTDecl(CGF) = VTTDecl; 845 } 846 } 847 848 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 849 /// Initialize the 'this' slot. 850 EmitThisParam(CGF); 851 852 /// Initialize the 'vtt' slot if needed. 853 if (getVTTDecl(CGF)) { 854 getVTTValue(CGF) 855 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)), 856 "vtt"); 857 } 858 859 /// If this is a function that the ABI specifies returns 'this', initialize 860 /// the return slot to 'this' at the start of the function. 861 /// 862 /// Unlike the setting of return types, this is done within the ABI 863 /// implementation instead of by clients of CGCXXABI because: 864 /// 1) getThisValue is currently protected 865 /// 2) in theory, an ABI could implement 'this' returns some other way; 866 /// HasThisReturn only specifies a contract, not the implementation 867 if (HasThisReturn(CGF.CurGD)) 868 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 869 } 870 871 void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF, 872 const CXXConstructorDecl *D, 873 CXXCtorType Type, 874 bool ForVirtualBase, bool Delegating, 875 llvm::Value *This, 876 CallExpr::const_arg_iterator ArgBeg, 877 CallExpr::const_arg_iterator ArgEnd) { 878 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, 879 Delegating); 880 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 881 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); 882 883 // FIXME: Provide a source location here. 884 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), 885 This, VTT, VTTTy, ArgBeg, ArgEnd); 886 } 887 888 void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 889 const CXXDestructorDecl *Dtor, 890 CXXDtorType DtorType, 891 SourceLocation CallLoc, 892 llvm::Value *This) { 893 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 894 895 const CGFunctionInfo *FInfo 896 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType); 897 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 898 llvm::Value *Callee 899 = CGF.BuildVirtualCall(GlobalDecl(Dtor, DtorType), This, Ty); 900 901 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This, 902 /*ImplicitParam=*/0, QualType(), 0, 0); 903 } 904 905 void ItaniumCXXABI::EmitVirtualInheritanceTables( 906 llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) { 907 CodeGenVTables &VTables = CGM.getVTables(); 908 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD); 909 VTables.EmitVTTDefinition(VTT, Linkage, RD); 910 } 911 912 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, 913 RValue RV, QualType ResultType) { 914 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl())) 915 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType); 916 917 // Destructor thunks in the ARM ABI have indeterminate results. 918 llvm::Type *T = 919 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType(); 920 RValue Undef = RValue::get(llvm::UndefValue::get(T)); 921 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType); 922 } 923 924 /************************** Array allocation cookies **************************/ 925 926 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) { 927 // The array cookie is a size_t; pad that up to the element alignment. 928 // The cookie is actually right-justified in that space. 929 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes), 930 CGM.getContext().getTypeAlignInChars(elementType)); 931 } 932 933 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 934 llvm::Value *NewPtr, 935 llvm::Value *NumElements, 936 const CXXNewExpr *expr, 937 QualType ElementType) { 938 assert(requiresArrayCookie(expr)); 939 940 unsigned AS = NewPtr->getType()->getPointerAddressSpace(); 941 942 ASTContext &Ctx = getContext(); 943 QualType SizeTy = Ctx.getSizeType(); 944 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy); 945 946 // The size of the cookie. 947 CharUnits CookieSize = 948 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType)); 949 assert(CookieSize == getArrayCookieSizeImpl(ElementType)); 950 951 // Compute an offset to the cookie. 952 llvm::Value *CookiePtr = NewPtr; 953 CharUnits CookieOffset = CookieSize - SizeSize; 954 if (!CookieOffset.isZero()) 955 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr, 956 CookieOffset.getQuantity()); 957 958 // Write the number of elements into the appropriate slot. 959 llvm::Value *NumElementsPtr 960 = CGF.Builder.CreateBitCast(CookiePtr, 961 CGF.ConvertType(SizeTy)->getPointerTo(AS)); 962 CGF.Builder.CreateStore(NumElements, NumElementsPtr); 963 964 // Finally, compute a pointer to the actual data buffer by skipping 965 // over the cookie completely. 966 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr, 967 CookieSize.getQuantity()); 968 } 969 970 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 971 llvm::Value *allocPtr, 972 CharUnits cookieSize) { 973 // The element size is right-justified in the cookie. 974 llvm::Value *numElementsPtr = allocPtr; 975 CharUnits numElementsOffset = 976 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes); 977 if (!numElementsOffset.isZero()) 978 numElementsPtr = 979 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr, 980 numElementsOffset.getQuantity()); 981 982 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 983 numElementsPtr = 984 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS)); 985 return CGF.Builder.CreateLoad(numElementsPtr); 986 } 987 988 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) { 989 // ARM says that the cookie is always: 990 // struct array_cookie { 991 // std::size_t element_size; // element_size != 0 992 // std::size_t element_count; 993 // }; 994 // But the base ABI doesn't give anything an alignment greater than 995 // 8, so we can dismiss this as typical ABI-author blindness to 996 // actual language complexity and round up to the element alignment. 997 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes), 998 CGM.getContext().getTypeAlignInChars(elementType)); 999 } 1000 1001 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1002 llvm::Value *newPtr, 1003 llvm::Value *numElements, 1004 const CXXNewExpr *expr, 1005 QualType elementType) { 1006 assert(requiresArrayCookie(expr)); 1007 1008 // NewPtr is a char*, but we generalize to arbitrary addrspaces. 1009 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 1010 1011 // The cookie is always at the start of the buffer. 1012 llvm::Value *cookie = newPtr; 1013 1014 // The first element is the element size. 1015 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS)); 1016 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy, 1017 getContext().getTypeSizeInChars(elementType).getQuantity()); 1018 CGF.Builder.CreateStore(elementSize, cookie); 1019 1020 // The second element is the element count. 1021 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1); 1022 CGF.Builder.CreateStore(numElements, cookie); 1023 1024 // Finally, compute a pointer to the actual data buffer by skipping 1025 // over the cookie completely. 1026 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType); 1027 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 1028 cookieSize.getQuantity()); 1029 } 1030 1031 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1032 llvm::Value *allocPtr, 1033 CharUnits cookieSize) { 1034 // The number of elements is at offset sizeof(size_t) relative to 1035 // the allocated pointer. 1036 llvm::Value *numElementsPtr 1037 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes); 1038 1039 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1040 numElementsPtr = 1041 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS)); 1042 return CGF.Builder.CreateLoad(numElementsPtr); 1043 } 1044 1045 /*********************** Static local initialization **************************/ 1046 1047 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM, 1048 llvm::PointerType *GuardPtrTy) { 1049 // int __cxa_guard_acquire(__guard *guard_object); 1050 llvm::FunctionType *FTy = 1051 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy), 1052 GuardPtrTy, /*isVarArg=*/false); 1053 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire", 1054 llvm::AttributeSet::get(CGM.getLLVMContext(), 1055 llvm::AttributeSet::FunctionIndex, 1056 llvm::Attribute::NoUnwind)); 1057 } 1058 1059 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM, 1060 llvm::PointerType *GuardPtrTy) { 1061 // void __cxa_guard_release(__guard *guard_object); 1062 llvm::FunctionType *FTy = 1063 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1064 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release", 1065 llvm::AttributeSet::get(CGM.getLLVMContext(), 1066 llvm::AttributeSet::FunctionIndex, 1067 llvm::Attribute::NoUnwind)); 1068 } 1069 1070 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM, 1071 llvm::PointerType *GuardPtrTy) { 1072 // void __cxa_guard_abort(__guard *guard_object); 1073 llvm::FunctionType *FTy = 1074 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1075 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort", 1076 llvm::AttributeSet::get(CGM.getLLVMContext(), 1077 llvm::AttributeSet::FunctionIndex, 1078 llvm::Attribute::NoUnwind)); 1079 } 1080 1081 namespace { 1082 struct CallGuardAbort : EHScopeStack::Cleanup { 1083 llvm::GlobalVariable *Guard; 1084 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {} 1085 1086 void Emit(CodeGenFunction &CGF, Flags flags) { 1087 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()), 1088 Guard); 1089 } 1090 }; 1091 } 1092 1093 /// The ARM code here follows the Itanium code closely enough that we 1094 /// just special-case it at particular places. 1095 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF, 1096 const VarDecl &D, 1097 llvm::GlobalVariable *var, 1098 bool shouldPerformInit) { 1099 CGBuilderTy &Builder = CGF.Builder; 1100 1101 // We only need to use thread-safe statics for local non-TLS variables; 1102 // global initialization is always single-threaded. 1103 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics && 1104 D.isLocalVarDecl() && !D.getTLSKind(); 1105 1106 // If we have a global variable with internal linkage and thread-safe statics 1107 // are disabled, we can just let the guard variable be of type i8. 1108 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage(); 1109 1110 llvm::IntegerType *guardTy; 1111 if (useInt8GuardVariable) { 1112 guardTy = CGF.Int8Ty; 1113 } else { 1114 // Guard variables are 64 bits in the generic ABI and size width on ARM 1115 // (i.e. 32-bit on AArch32, 64-bit on AArch64). 1116 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty); 1117 } 1118 llvm::PointerType *guardPtrTy = guardTy->getPointerTo(); 1119 1120 // Create the guard variable if we don't already have it (as we 1121 // might if we're double-emitting this function body). 1122 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D); 1123 if (!guard) { 1124 // Mangle the name for the guard. 1125 SmallString<256> guardName; 1126 { 1127 llvm::raw_svector_ostream out(guardName); 1128 getMangleContext().mangleItaniumGuardVariable(&D, out); 1129 out.flush(); 1130 } 1131 1132 // Create the guard variable with a zero-initializer. 1133 // Just absorb linkage and visibility from the guarded variable. 1134 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy, 1135 false, var->getLinkage(), 1136 llvm::ConstantInt::get(guardTy, 0), 1137 guardName.str()); 1138 guard->setVisibility(var->getVisibility()); 1139 // If the variable is thread-local, so is its guard variable. 1140 guard->setThreadLocalMode(var->getThreadLocalMode()); 1141 1142 CGM.setStaticLocalDeclGuardAddress(&D, guard); 1143 } 1144 1145 // Test whether the variable has completed initialization. 1146 llvm::Value *isInitialized; 1147 1148 // ARM C++ ABI 3.2.3.1: 1149 // To support the potential use of initialization guard variables 1150 // as semaphores that are the target of ARM SWP and LDREX/STREX 1151 // synchronizing instructions we define a static initialization 1152 // guard variable to be a 4-byte aligned, 4- byte word with the 1153 // following inline access protocol. 1154 // #define INITIALIZED 1 1155 // if ((obj_guard & INITIALIZED) != INITIALIZED) { 1156 // if (__cxa_guard_acquire(&obj_guard)) 1157 // ... 1158 // } 1159 if (UseARMGuardVarABI && !useInt8GuardVariable) { 1160 llvm::Value *V = Builder.CreateLoad(guard); 1161 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1); 1162 V = Builder.CreateAnd(V, Test1); 1163 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized"); 1164 1165 // Itanium C++ ABI 3.3.2: 1166 // The following is pseudo-code showing how these functions can be used: 1167 // if (obj_guard.first_byte == 0) { 1168 // if ( __cxa_guard_acquire (&obj_guard) ) { 1169 // try { 1170 // ... initialize the object ...; 1171 // } catch (...) { 1172 // __cxa_guard_abort (&obj_guard); 1173 // throw; 1174 // } 1175 // ... queue object destructor with __cxa_atexit() ...; 1176 // __cxa_guard_release (&obj_guard); 1177 // } 1178 // } 1179 } else { 1180 // Load the first byte of the guard variable. 1181 llvm::LoadInst *LI = 1182 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy)); 1183 LI->setAlignment(1); 1184 1185 // Itanium ABI: 1186 // An implementation supporting thread-safety on multiprocessor 1187 // systems must also guarantee that references to the initialized 1188 // object do not occur before the load of the initialization flag. 1189 // 1190 // In LLVM, we do this by marking the load Acquire. 1191 if (threadsafe) 1192 LI->setAtomic(llvm::Acquire); 1193 1194 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized"); 1195 } 1196 1197 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check"); 1198 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1199 1200 // Check if the first byte of the guard variable is zero. 1201 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock); 1202 1203 CGF.EmitBlock(InitCheckBlock); 1204 1205 // Variables used when coping with thread-safe statics and exceptions. 1206 if (threadsafe) { 1207 // Call __cxa_guard_acquire. 1208 llvm::Value *V 1209 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard); 1210 1211 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1212 1213 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"), 1214 InitBlock, EndBlock); 1215 1216 // Call __cxa_guard_abort along the exceptional edge. 1217 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard); 1218 1219 CGF.EmitBlock(InitBlock); 1220 } 1221 1222 // Emit the initializer and add a global destructor if appropriate. 1223 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit); 1224 1225 if (threadsafe) { 1226 // Pop the guard-abort cleanup if we pushed one. 1227 CGF.PopCleanupBlock(); 1228 1229 // Call __cxa_guard_release. This cannot throw. 1230 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard); 1231 } else { 1232 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard); 1233 } 1234 1235 CGF.EmitBlock(EndBlock); 1236 } 1237 1238 /// Register a global destructor using __cxa_atexit. 1239 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF, 1240 llvm::Constant *dtor, 1241 llvm::Constant *addr, 1242 bool TLS) { 1243 const char *Name = "__cxa_atexit"; 1244 if (TLS) { 1245 const llvm::Triple &T = CGF.getTarget().getTriple(); 1246 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit"; 1247 } 1248 1249 // We're assuming that the destructor function is something we can 1250 // reasonably call with the default CC. Go ahead and cast it to the 1251 // right prototype. 1252 llvm::Type *dtorTy = 1253 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo(); 1254 1255 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d); 1256 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy }; 1257 llvm::FunctionType *atexitTy = 1258 llvm::FunctionType::get(CGF.IntTy, paramTys, false); 1259 1260 // Fetch the actual function. 1261 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name); 1262 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit)) 1263 fn->setDoesNotThrow(); 1264 1265 // Create a variable that binds the atexit to this shared object. 1266 llvm::Constant *handle = 1267 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle"); 1268 1269 llvm::Value *args[] = { 1270 llvm::ConstantExpr::getBitCast(dtor, dtorTy), 1271 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy), 1272 handle 1273 }; 1274 CGF.EmitNounwindRuntimeCall(atexit, args); 1275 } 1276 1277 /// Register a global destructor as best as we know how. 1278 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, 1279 const VarDecl &D, 1280 llvm::Constant *dtor, 1281 llvm::Constant *addr) { 1282 // Use __cxa_atexit if available. 1283 if (CGM.getCodeGenOpts().CXAAtExit) 1284 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind()); 1285 1286 if (D.getTLSKind()) 1287 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction"); 1288 1289 // In Apple kexts, we want to add a global destructor entry. 1290 // FIXME: shouldn't this be guarded by some variable? 1291 if (CGM.getLangOpts().AppleKext) { 1292 // Generate a global destructor entry. 1293 return CGM.AddCXXDtorEntry(dtor, addr); 1294 } 1295 1296 CGF.registerGlobalDtorWithAtExit(dtor, addr); 1297 } 1298 1299 /// Get the appropriate linkage for the wrapper function. This is essentially 1300 /// the weak form of the variable's linkage; every translation unit which wneeds 1301 /// the wrapper emits a copy, and we want the linker to merge them. 1302 static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage( 1303 llvm::GlobalValue::LinkageTypes VarLinkage) { 1304 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage)) 1305 return llvm::GlobalValue::LinkerPrivateWeakLinkage; 1306 // For internal linkage variables, we don't need an external or weak wrapper. 1307 if (llvm::GlobalValue::isLocalLinkage(VarLinkage)) 1308 return VarLinkage; 1309 return llvm::GlobalValue::WeakODRLinkage; 1310 } 1311 1312 llvm::Function * 1313 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD, 1314 llvm::GlobalVariable *Var) { 1315 // Mangle the name for the thread_local wrapper function. 1316 SmallString<256> WrapperName; 1317 { 1318 llvm::raw_svector_ostream Out(WrapperName); 1319 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out); 1320 Out.flush(); 1321 } 1322 1323 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName)) 1324 return cast<llvm::Function>(V); 1325 1326 llvm::Type *RetTy = Var->getType(); 1327 if (VD->getType()->isReferenceType()) 1328 RetTy = RetTy->getPointerElementType(); 1329 1330 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false); 1331 llvm::Function *Wrapper = llvm::Function::Create( 1332 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(), 1333 &CGM.getModule()); 1334 // Always resolve references to the wrapper at link time. 1335 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility); 1336 return Wrapper; 1337 } 1338 1339 void ItaniumCXXABI::EmitThreadLocalInitFuncs( 1340 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls, 1341 llvm::Function *InitFunc) { 1342 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 1343 const VarDecl *VD = Decls[I].first; 1344 llvm::GlobalVariable *Var = Decls[I].second; 1345 1346 // Mangle the name for the thread_local initialization function. 1347 SmallString<256> InitFnName; 1348 { 1349 llvm::raw_svector_ostream Out(InitFnName); 1350 getMangleContext().mangleItaniumThreadLocalInit(VD, Out); 1351 Out.flush(); 1352 } 1353 1354 // If we have a definition for the variable, emit the initialization 1355 // function as an alias to the global Init function (if any). Otherwise, 1356 // produce a declaration of the initialization function. 1357 llvm::GlobalValue *Init = 0; 1358 bool InitIsInitFunc = false; 1359 if (VD->hasDefinition()) { 1360 InitIsInitFunc = true; 1361 if (InitFunc) 1362 Init = 1363 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(), 1364 InitFnName.str(), InitFunc, &CGM.getModule()); 1365 } else { 1366 // Emit a weak global function referring to the initialization function. 1367 // This function will not exist if the TU defining the thread_local 1368 // variable in question does not need any dynamic initialization for 1369 // its thread_local variables. 1370 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false); 1371 Init = llvm::Function::Create( 1372 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(), 1373 &CGM.getModule()); 1374 } 1375 1376 if (Init) 1377 Init->setVisibility(Var->getVisibility()); 1378 1379 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var); 1380 llvm::LLVMContext &Context = CGM.getModule().getContext(); 1381 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper); 1382 CGBuilderTy Builder(Entry); 1383 if (InitIsInitFunc) { 1384 if (Init) 1385 Builder.CreateCall(Init); 1386 } else { 1387 // Don't know whether we have an init function. Call it if it exists. 1388 llvm::Value *Have = Builder.CreateIsNotNull(Init); 1389 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 1390 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 1391 Builder.CreateCondBr(Have, InitBB, ExitBB); 1392 1393 Builder.SetInsertPoint(InitBB); 1394 Builder.CreateCall(Init); 1395 Builder.CreateBr(ExitBB); 1396 1397 Builder.SetInsertPoint(ExitBB); 1398 } 1399 1400 // For a reference, the result of the wrapper function is a pointer to 1401 // the referenced object. 1402 llvm::Value *Val = Var; 1403 if (VD->getType()->isReferenceType()) { 1404 llvm::LoadInst *LI = Builder.CreateLoad(Val); 1405 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity()); 1406 Val = LI; 1407 } 1408 1409 Builder.CreateRet(Val); 1410 } 1411 } 1412 1413 LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF, 1414 const DeclRefExpr *DRE) { 1415 const VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1416 QualType T = VD->getType(); 1417 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T); 1418 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty); 1419 llvm::Function *Wrapper = 1420 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val)); 1421 1422 Val = CGF.Builder.CreateCall(Wrapper); 1423 1424 LValue LV; 1425 if (VD->getType()->isReferenceType()) 1426 LV = CGF.MakeNaturalAlignAddrLValue(Val, T); 1427 else 1428 LV = CGF.MakeAddrLValue(Val, DRE->getType(), 1429 CGF.getContext().getDeclAlign(VD)); 1430 // FIXME: need setObjCGCLValueClass? 1431 return LV; 1432 } 1433 1434 /// Return whether the given global decl needs a VTT parameter, which it does 1435 /// if it's a base constructor or destructor with virtual bases. 1436 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) { 1437 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1438 1439 // We don't have any virtual bases, just return early. 1440 if (!MD->getParent()->getNumVBases()) 1441 return false; 1442 1443 // Check if we have a base constructor. 1444 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base) 1445 return true; 1446 1447 // Check if we have a base destructor. 1448 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 1449 return true; 1450 1451 return false; 1452 } 1453