1218893Sdim//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9193326Sed// 10193326Sed// This contains code dealing with C++ code generation. 11193326Sed// 12193326Sed//===----------------------------------------------------------------------===// 13193326Sed 14198092Srdivacky// We might split this into multiple files if it gets too unwieldy 15193326Sed 16249423Sdim#include "CodeGenModule.h" 17208600Srdivacky#include "CGCXXABI.h" 18193326Sed#include "CodeGenFunction.h" 19193326Sed#include "clang/AST/ASTContext.h" 20193326Sed#include "clang/AST/Decl.h" 21193326Sed#include "clang/AST/DeclCXX.h" 22193326Sed#include "clang/AST/DeclObjC.h" 23218893Sdim#include "clang/AST/Mangle.h" 24249423Sdim#include "clang/AST/RecordLayout.h" 25198092Srdivacky#include "clang/AST/StmtCXX.h" 26210299Sed#include "clang/Frontend/CodeGenOptions.h" 27193326Sed#include "llvm/ADT/StringExtras.h" 28193326Sedusing namespace clang; 29193326Sedusing namespace CodeGen; 30193326Sed 31204643Srdivacky/// Try to emit a base destructor as an alias to its primary 32204643Srdivacky/// base-class destructor. 33204643Srdivackybool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) { 34204643Srdivacky if (!getCodeGenOpts().CXXCtorDtorAliases) 35204643Srdivacky return true; 36198092Srdivacky 37263508Sdim // Producing an alias to a base class ctor/dtor can degrade debug quality 38263508Sdim // as the debugger cannot tell them appart. 39263508Sdim if (getCodeGenOpts().OptimizationLevel == 0) 40263508Sdim return true; 41263508Sdim 42204643Srdivacky // If the destructor doesn't have a trivial body, we have to emit it 43204643Srdivacky // separately. 44223017Sdim if (!D->hasTrivialBody()) 45204643Srdivacky return true; 46198092Srdivacky 47204643Srdivacky const CXXRecordDecl *Class = D->getParent(); 48204643Srdivacky 49204643Srdivacky // If we need to manipulate a VTT parameter, give up. 50204643Srdivacky if (Class->getNumVBases()) { 51204643Srdivacky // Extra Credit: passing extra parameters is perfectly safe 52204643Srdivacky // in many calling conventions, so only bail out if the ctor's 53204643Srdivacky // calling convention is nonstandard. 54204643Srdivacky return true; 55204643Srdivacky } 56204643Srdivacky 57218893Sdim // If any field has a non-trivial destructor, we have to emit the 58218893Sdim // destructor separately. 59204643Srdivacky for (CXXRecordDecl::field_iterator I = Class->field_begin(), 60204643Srdivacky E = Class->field_end(); I != E; ++I) 61239462Sdim if (I->getType().isDestructedType()) 62218893Sdim return true; 63204643Srdivacky 64204643Srdivacky // Try to find a unique base class with a non-trivial destructor. 65204643Srdivacky const CXXRecordDecl *UniqueBase = 0; 66204643Srdivacky for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(), 67204643Srdivacky E = Class->bases_end(); I != E; ++I) { 68204643Srdivacky 69204643Srdivacky // We're in the base destructor, so skip virtual bases. 70204643Srdivacky if (I->isVirtual()) continue; 71204643Srdivacky 72204643Srdivacky // Skip base classes with trivial destructors. 73204643Srdivacky const CXXRecordDecl *Base 74204643Srdivacky = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 75204643Srdivacky if (Base->hasTrivialDestructor()) continue; 76204643Srdivacky 77204643Srdivacky // If we've already found a base class with a non-trivial 78204643Srdivacky // destructor, give up. 79204643Srdivacky if (UniqueBase) return true; 80204643Srdivacky UniqueBase = Base; 81204643Srdivacky } 82204643Srdivacky 83204643Srdivacky // If we didn't find any bases with a non-trivial destructor, then 84204643Srdivacky // the base destructor is actually effectively trivial, which can 85204643Srdivacky // happen if it was needlessly user-defined or if there are virtual 86204643Srdivacky // bases with non-trivial destructors. 87204643Srdivacky if (!UniqueBase) 88204643Srdivacky return true; 89204643Srdivacky 90204643Srdivacky // If the base is at a non-zero offset, give up. 91204643Srdivacky const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class); 92239462Sdim if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero()) 93204643Srdivacky return true; 94204643Srdivacky 95263508Sdim // Give up if the calling conventions don't match. We could update the call, 96263508Sdim // but it is probably not worth it. 97263508Sdim const CXXDestructorDecl *BaseD = UniqueBase->getDestructor(); 98263508Sdim if (BaseD->getType()->getAs<FunctionType>()->getCallConv() != 99263508Sdim D->getType()->getAs<FunctionType>()->getCallConv()) 100263508Sdim return true; 101263508Sdim 102204643Srdivacky return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base), 103263508Sdim GlobalDecl(BaseD, Dtor_Base), 104263508Sdim false); 105193326Sed} 106193326Sed 107204643Srdivacky/// Try to emit a definition as a global alias for another definition. 108263508Sdim/// If \p InEveryTU is true, we know that an equivalent alias can be produced 109263508Sdim/// in every translation unit. 110204643Srdivackybool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl, 111263508Sdim GlobalDecl TargetDecl, 112263508Sdim bool InEveryTU) { 113204643Srdivacky if (!getCodeGenOpts().CXXCtorDtorAliases) 114204643Srdivacky return true; 115204643Srdivacky 116204643Srdivacky // The alias will use the linkage of the referrent. If we can't 117204643Srdivacky // support aliases with that linkage, fail. 118263508Sdim llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl); 119204643Srdivacky 120263508Sdim // We can't use an alias if the linkage is not valid for one. 121263508Sdim if (!llvm::GlobalAlias::isValidLinkage(Linkage)) 122204643Srdivacky return true; 123204643Srdivacky 124263508Sdim llvm::GlobalValue::LinkageTypes TargetLinkage = 125263508Sdim getFunctionLinkage(TargetDecl); 126204643Srdivacky 127263508Sdim // Check if we have it already. 128263508Sdim StringRef MangledName = getMangledName(AliasDecl); 129263508Sdim llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 130263508Sdim if (Entry && !Entry->isDeclaration()) 131263508Sdim return false; 132263508Sdim if (Replacements.count(MangledName)) 133263508Sdim return false; 134204793Srdivacky 135204643Srdivacky // Derive the type for the alias. 136226633Sdim llvm::PointerType *AliasType 137204643Srdivacky = getTypes().GetFunctionType(AliasDecl)->getPointerTo(); 138204643Srdivacky 139204643Srdivacky // Find the referrent. Some aliases might require a bitcast, in 140204643Srdivacky // which case the caller is responsible for ensuring the soundness 141204643Srdivacky // of these semantics. 142204643Srdivacky llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl)); 143204643Srdivacky llvm::Constant *Aliasee = Ref; 144204643Srdivacky if (Ref->getType() != AliasType) 145204643Srdivacky Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType); 146204643Srdivacky 147263508Sdim // Instead of creating as alias to a linkonce_odr, replace all of the uses 148263508Sdim // of the aliassee. 149263508Sdim if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) && 150263508Sdim (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage || 151263508Sdim !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) { 152263508Sdim // FIXME: An extern template instanciation will create functions with 153263508Sdim // linkage "AvailableExternally". In libc++, some classes also define 154263508Sdim // members with attribute "AlwaysInline" and expect no reference to 155263508Sdim // be generated. It is desirable to reenable this optimisation after 156263508Sdim // corresponding LLVM changes. 157263508Sdim Replacements[MangledName] = Aliasee; 158263508Sdim return false; 159263508Sdim } 160263508Sdim 161263508Sdim if (!InEveryTU) { 162263508Sdim /// If we don't have a definition for the destructor yet, don't 163263508Sdim /// emit. We can't emit aliases to declarations; that's just not 164263508Sdim /// how aliases work. 165263508Sdim if (Ref->isDeclaration()) 166263508Sdim return true; 167263508Sdim } 168263508Sdim 169263508Sdim // Don't create an alias to a linker weak symbol. This avoids producing 170263508Sdim // different COMDATs in different TUs. Another option would be to 171263508Sdim // output the alias both for weak_odr and linkonce_odr, but that 172263508Sdim // requires explicit comdat support in the IL. 173263508Sdim if (llvm::GlobalValue::isWeakForLinker(TargetLinkage)) 174263508Sdim return true; 175263508Sdim 176204643Srdivacky // Create the alias with no name. 177204643Srdivacky llvm::GlobalAlias *Alias = 178204643Srdivacky new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule()); 179204643Srdivacky 180204643Srdivacky // Switch any previous uses to the alias. 181204643Srdivacky if (Entry) { 182204643Srdivacky assert(Entry->getType() == AliasType && 183204643Srdivacky "declaration exists with different type"); 184205408Srdivacky Alias->takeName(Entry); 185204643Srdivacky Entry->replaceAllUsesWith(Alias); 186204643Srdivacky Entry->eraseFromParent(); 187205408Srdivacky } else { 188210299Sed Alias->setName(MangledName); 189204643Srdivacky } 190204643Srdivacky 191204643Srdivacky // Finally, set up the alias with its proper name and attributes. 192218893Sdim SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias); 193204643Srdivacky 194204643Srdivacky return false; 195204643Srdivacky} 196204643Srdivacky 197221345Sdimvoid CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor, 198221345Sdim CXXCtorType ctorType) { 199204643Srdivacky // The complete constructor is equivalent to the base constructor 200204643Srdivacky // for classes with no virtual bases. Try to emit it as an alias. 201249423Sdim if (getTarget().getCXXABI().hasConstructorVariants() && 202221345Sdim !ctor->getParent()->getNumVBases() && 203263508Sdim (ctorType == Ctor_Complete || ctorType == Ctor_Base)) { 204263508Sdim bool ProducedAlias = 205263508Sdim !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete), 206263508Sdim GlobalDecl(ctor, Ctor_Base), true); 207263508Sdim if (ctorType == Ctor_Complete && ProducedAlias) 208263508Sdim return; 209263508Sdim } 210198092Srdivacky 211234353Sdim const CGFunctionInfo &fnInfo = 212234353Sdim getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType); 213198092Srdivacky 214221345Sdim llvm::Function *fn = 215221345Sdim cast<llvm::Function>(GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo)); 216263508Sdim setFunctionLinkage(GlobalDecl(ctor, ctorType), fn); 217198092Srdivacky 218221345Sdim CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo); 219221345Sdim 220221345Sdim SetFunctionDefinitionAttributes(ctor, fn); 221221345Sdim SetLLVMFunctionAttributesForDefinition(ctor, fn); 222193326Sed} 223193326Sed 224204643Srdivackyllvm::GlobalValue * 225221345SdimCodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, 226221345Sdim CXXCtorType ctorType, 227221345Sdim const CGFunctionInfo *fnInfo) { 228221345Sdim GlobalDecl GD(ctor, ctorType); 229210299Sed 230226633Sdim StringRef name = getMangledName(GD); 231221345Sdim if (llvm::GlobalValue *existing = GetGlobalValue(name)) 232221345Sdim return existing; 233204643Srdivacky 234234353Sdim if (!fnInfo) 235234353Sdim fnInfo = &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType); 236221345Sdim 237234353Sdim llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo); 238221345Sdim return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD, 239218893Sdim /*ForVTable=*/false)); 240193326Sed} 241193326Sed 242221345Sdimvoid CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *dtor, 243221345Sdim CXXDtorType dtorType) { 244204643Srdivacky // The complete destructor is equivalent to the base destructor for 245204643Srdivacky // classes with no virtual bases, so try to emit it as an alias. 246263508Sdim if (!dtor->getParent()->getNumVBases() && 247263508Sdim (dtorType == Dtor_Complete || dtorType == Dtor_Base)) { 248263508Sdim bool ProducedAlias = 249263508Sdim !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete), 250263508Sdim GlobalDecl(dtor, Dtor_Base), true); 251263508Sdim if (ProducedAlias) { 252263508Sdim if (dtorType == Dtor_Complete) 253263508Sdim return; 254263508Sdim if (dtor->isVirtual()) 255263508Sdim getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete)); 256263508Sdim } 257263508Sdim } 258198092Srdivacky 259204643Srdivacky // The base destructor is equivalent to the base destructor of its 260204643Srdivacky // base class if there is exactly one non-virtual base class with a 261204643Srdivacky // non-trivial destructor, there are no fields with a non-trivial 262204643Srdivacky // destructor, and the body of the destructor is trivial. 263221345Sdim if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor)) 264204643Srdivacky return; 265204643Srdivacky 266234353Sdim const CGFunctionInfo &fnInfo = 267234353Sdim getTypes().arrangeCXXDestructor(dtor, dtorType); 268204643Srdivacky 269221345Sdim llvm::Function *fn = 270221345Sdim cast<llvm::Function>(GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo)); 271263508Sdim setFunctionLinkage(GlobalDecl(dtor, dtorType), fn); 272198092Srdivacky 273221345Sdim CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo); 274221345Sdim 275221345Sdim SetFunctionDefinitionAttributes(dtor, fn); 276221345Sdim SetLLVMFunctionAttributesForDefinition(dtor, fn); 277193326Sed} 278193326Sed 279204643Srdivackyllvm::GlobalValue * 280221345SdimCodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor, 281221345Sdim CXXDtorType dtorType, 282263508Sdim const CGFunctionInfo *fnInfo, 283263508Sdim llvm::FunctionType *fnType) { 284221345Sdim GlobalDecl GD(dtor, dtorType); 285210299Sed 286226633Sdim StringRef name = getMangledName(GD); 287221345Sdim if (llvm::GlobalValue *existing = GetGlobalValue(name)) 288221345Sdim return existing; 289204643Srdivacky 290263508Sdim if (!fnType) { 291263508Sdim if (!fnInfo) fnInfo = &getTypes().arrangeCXXDestructor(dtor, dtorType); 292263508Sdim fnType = getTypes().GetFunctionType(*fnInfo); 293263508Sdim } 294221345Sdim return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD, 295218893Sdim /*ForVTable=*/false)); 296193326Sed} 297193326Sed 298263508Sdimstatic llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF, 299263508Sdim GlobalDecl GD, 300263508Sdim llvm::Type *Ty, 301263508Sdim const CXXRecordDecl *RD) { 302263508Sdim assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() && 303263508Sdim "No kext in Microsoft ABI"); 304263508Sdim GD = GD.getCanonicalDecl(); 305263508Sdim CodeGenModule &CGM = CGF.CGM; 306263508Sdim llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits()); 307218893Sdim Ty = Ty->getPointerTo()->getPointerTo(); 308263508Sdim VTable = CGF.Builder.CreateBitCast(VTable, Ty); 309263508Sdim assert(VTable && "BuildVirtualCall = kext vtbl pointer is null"); 310263508Sdim uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); 311263508Sdim uint64_t AddressPoint = 312263508Sdim CGM.getItaniumVTableContext().getVTableLayout(RD) 313263508Sdim .getAddressPoint(BaseSubobject(RD, CharUnits::Zero())); 314263508Sdim VTableIndex += AddressPoint; 315263508Sdim llvm::Value *VFuncPtr = 316263508Sdim CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt"); 317199482Srdivacky return CGF.Builder.CreateLoad(VFuncPtr); 318199482Srdivacky} 319199482Srdivacky 320263508Sdim/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making 321218893Sdim/// indirect call to virtual functions. It makes the call through indexing 322218893Sdim/// into the vtable. 323199482Srdivackyllvm::Value * 324218893SdimCodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 325218893Sdim NestedNameSpecifier *Qual, 326226633Sdim llvm::Type *Ty) { 327218893Sdim assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) && 328218893Sdim "BuildAppleKextVirtualCall - bad Qual kind"); 329218893Sdim 330218893Sdim const Type *QTy = Qual->getAsType(); 331218893Sdim QualType T = QualType(QTy, 0); 332218893Sdim const RecordType *RT = T->getAs<RecordType>(); 333218893Sdim assert(RT && "BuildAppleKextVirtualCall - Qual type must be record"); 334218893Sdim const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 335218893Sdim 336218893Sdim if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) 337218893Sdim return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD); 338263508Sdim 339263508Sdim return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD); 340199482Srdivacky} 341208600Srdivacky 342218893Sdim/// BuildVirtualCall - This routine makes indirect vtable call for 343218893Sdim/// call to virtual destructors. It returns 0 if it could not do it. 344218893Sdimllvm::Value * 345218893SdimCodeGenFunction::BuildAppleKextVirtualDestructorCall( 346218893Sdim const CXXDestructorDecl *DD, 347218893Sdim CXXDtorType Type, 348218893Sdim const CXXRecordDecl *RD) { 349218893Sdim const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD); 350218893Sdim // FIXME. Dtor_Base dtor is always direct!! 351218893Sdim // It need be somehow inline expanded into the caller. 352218893Sdim // -O does that. But need to support -O0 as well. 353218893Sdim if (MD->isVirtual() && Type != Dtor_Base) { 354218893Sdim // Compute the function type we're calling. 355263508Sdim const CGFunctionInfo &FInfo = 356263508Sdim CGM.getTypes().arrangeCXXDestructor(DD, Dtor_Complete); 357234353Sdim llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo); 358263508Sdim return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD); 359218893Sdim } 360263508Sdim return 0; 361212904Sdim} 362