1 //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===// 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 contains code dealing with C++ code generation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 // We might split this into multiple files if it gets too unwieldy 15 16 #include "CodeGenModule.h" 17 #include "CGCXXABI.h" 18 #include "CodeGenFunction.h" 19 #include "clang/AST/ASTContext.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/Mangle.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/StmtCXX.h" 26 #include "clang/Frontend/CodeGenOptions.h" 27 #include "llvm/ADT/StringExtras.h" 28 using namespace clang; 29 using namespace CodeGen; 30 31 /// Try to emit a base destructor as an alias to its primary 32 /// base-class destructor. 33 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) { 34 if (!getCodeGenOpts().CXXCtorDtorAliases) 35 return true; 36 37 // Producing an alias to a base class ctor/dtor can degrade debug quality 38 // as the debugger cannot tell them apart. 39 if (getCodeGenOpts().OptimizationLevel == 0) 40 return true; 41 42 // If the destructor doesn't have a trivial body, we have to emit it 43 // separately. 44 if (!D->hasTrivialBody()) 45 return true; 46 47 const CXXRecordDecl *Class = D->getParent(); 48 49 // If we need to manipulate a VTT parameter, give up. 50 if (Class->getNumVBases()) { 51 // Extra Credit: passing extra parameters is perfectly safe 52 // in many calling conventions, so only bail out if the ctor's 53 // calling convention is nonstandard. 54 return true; 55 } 56 57 // If any field has a non-trivial destructor, we have to emit the 58 // destructor separately. 59 for (const auto *I : Class->fields()) 60 if (I->getType().isDestructedType()) 61 return true; 62 63 // Try to find a unique base class with a non-trivial destructor. 64 const CXXRecordDecl *UniqueBase = nullptr; 65 for (const auto &I : Class->bases()) { 66 67 // We're in the base destructor, so skip virtual bases. 68 if (I.isVirtual()) continue; 69 70 // Skip base classes with trivial destructors. 71 const auto *Base = 72 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 73 if (Base->hasTrivialDestructor()) continue; 74 75 // If we've already found a base class with a non-trivial 76 // destructor, give up. 77 if (UniqueBase) return true; 78 UniqueBase = Base; 79 } 80 81 // If we didn't find any bases with a non-trivial destructor, then 82 // the base destructor is actually effectively trivial, which can 83 // happen if it was needlessly user-defined or if there are virtual 84 // bases with non-trivial destructors. 85 if (!UniqueBase) 86 return true; 87 88 // If the base is at a non-zero offset, give up. 89 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class); 90 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero()) 91 return true; 92 93 // Give up if the calling conventions don't match. We could update the call, 94 // but it is probably not worth it. 95 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor(); 96 if (BaseD->getType()->getAs<FunctionType>()->getCallConv() != 97 D->getType()->getAs<FunctionType>()->getCallConv()) 98 return true; 99 100 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base), 101 GlobalDecl(BaseD, Dtor_Base), 102 false); 103 } 104 105 /// Try to emit a definition as a global alias for another definition. 106 /// If \p InEveryTU is true, we know that an equivalent alias can be produced 107 /// in every translation unit. 108 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl, 109 GlobalDecl TargetDecl, 110 bool InEveryTU) { 111 if (!getCodeGenOpts().CXXCtorDtorAliases) 112 return true; 113 114 // The alias will use the linkage of the referent. If we can't 115 // support aliases with that linkage, fail. 116 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl); 117 118 // We can't use an alias if the linkage is not valid for one. 119 if (!llvm::GlobalAlias::isValidLinkage(Linkage)) 120 return true; 121 122 llvm::GlobalValue::LinkageTypes TargetLinkage = 123 getFunctionLinkage(TargetDecl); 124 125 // Check if we have it already. 126 StringRef MangledName = getMangledName(AliasDecl); 127 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 128 if (Entry && !Entry->isDeclaration()) 129 return false; 130 if (Replacements.count(MangledName)) 131 return false; 132 133 // Derive the type for the alias. 134 llvm::PointerType *AliasType 135 = getTypes().GetFunctionType(AliasDecl)->getPointerTo(); 136 137 // Find the referent. Some aliases might require a bitcast, in 138 // which case the caller is responsible for ensuring the soundness 139 // of these semantics. 140 auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl)); 141 auto *Aliasee = dyn_cast<llvm::GlobalObject>(Ref); 142 if (!Aliasee) 143 Aliasee = cast<llvm::GlobalAlias>(Ref)->getAliasee(); 144 145 // Instead of creating as alias to a linkonce_odr, replace all of the uses 146 // of the aliasee. 147 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) && 148 (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage || 149 !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) { 150 // FIXME: An extern template instantiation will create functions with 151 // linkage "AvailableExternally". In libc++, some classes also define 152 // members with attribute "AlwaysInline" and expect no reference to 153 // be generated. It is desirable to reenable this optimisation after 154 // corresponding LLVM changes. 155 llvm::Constant *Replacement = Aliasee; 156 if (Aliasee->getType() != AliasType) 157 Replacement = llvm::ConstantExpr::getBitCast(Aliasee, AliasType); 158 Replacements[MangledName] = Replacement; 159 return false; 160 } 161 162 if (!InEveryTU) { 163 /// If we don't have a definition for the destructor yet, don't 164 /// emit. We can't emit aliases to declarations; that's just not 165 /// how aliases work. 166 if (Aliasee->isDeclaration()) 167 return true; 168 } 169 170 // Don't create an alias to a linker weak symbol. This avoids producing 171 // different COMDATs in different TUs. Another option would be to 172 // output the alias both for weak_odr and linkonce_odr, but that 173 // requires explicit comdat support in the IL. 174 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage)) 175 return true; 176 177 // Create the alias with no name. 178 auto *Alias = llvm::GlobalAlias::create(AliasType->getElementType(), 0, 179 Linkage, "", Aliasee); 180 181 // Switch any previous uses to the alias. 182 if (Entry) { 183 assert(Entry->getType() == AliasType && 184 "declaration exists with different type"); 185 Alias->takeName(Entry); 186 Entry->replaceAllUsesWith(Alias); 187 Entry->eraseFromParent(); 188 } else { 189 Alias->setName(MangledName); 190 } 191 192 // Finally, set up the alias with its proper name and attributes. 193 SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias); 194 195 return false; 196 } 197 198 void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor, 199 CXXCtorType ctorType) { 200 if (!getTarget().getCXXABI().hasConstructorVariants()) { 201 // If there are no constructor variants, always emit the complete destructor. 202 ctorType = Ctor_Complete; 203 } else if (!ctor->getParent()->getNumVBases() && 204 (ctorType == Ctor_Complete || ctorType == Ctor_Base)) { 205 // The complete constructor is equivalent to the base constructor 206 // for classes with no virtual bases. Try to emit it as an alias. 207 bool ProducedAlias = 208 !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete), 209 GlobalDecl(ctor, Ctor_Base), true); 210 if (ctorType == Ctor_Complete && ProducedAlias) 211 return; 212 } 213 214 const CGFunctionInfo &fnInfo = 215 getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType); 216 217 auto *fn = cast<llvm::Function>( 218 GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo, true)); 219 setFunctionLinkage(GlobalDecl(ctor, ctorType), fn); 220 221 CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo); 222 223 setFunctionDefinitionAttributes(ctor, fn); 224 SetLLVMFunctionAttributesForDefinition(ctor, fn); 225 } 226 227 llvm::GlobalValue * 228 CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor, 229 CXXCtorType ctorType, 230 const CGFunctionInfo *fnInfo, 231 bool DontDefer) { 232 GlobalDecl GD(ctor, ctorType); 233 234 StringRef name = getMangledName(GD); 235 if (llvm::GlobalValue *existing = GetGlobalValue(name)) 236 return existing; 237 238 if (!fnInfo) 239 fnInfo = &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType); 240 241 llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo); 242 return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD, 243 /*ForVTable=*/false, 244 DontDefer)); 245 } 246 247 void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *dtor, 248 CXXDtorType dtorType) { 249 // The complete destructor is equivalent to the base destructor for 250 // classes with no virtual bases, so try to emit it as an alias. 251 if (!dtor->getParent()->getNumVBases() && 252 (dtorType == Dtor_Complete || dtorType == Dtor_Base)) { 253 bool ProducedAlias = 254 !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete), 255 GlobalDecl(dtor, Dtor_Base), true); 256 if (ProducedAlias) { 257 if (dtorType == Dtor_Complete) 258 return; 259 if (dtor->isVirtual()) 260 getVTables().EmitThunks(GlobalDecl(dtor, Dtor_Complete)); 261 } 262 } 263 264 // The base destructor is equivalent to the base destructor of its 265 // base class if there is exactly one non-virtual base class with a 266 // non-trivial destructor, there are no fields with a non-trivial 267 // destructor, and the body of the destructor is trivial. 268 if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor)) 269 return; 270 271 const CGFunctionInfo &fnInfo = 272 getTypes().arrangeCXXDestructor(dtor, dtorType); 273 274 auto *fn = cast<llvm::Function>( 275 GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo, nullptr, true)); 276 setFunctionLinkage(GlobalDecl(dtor, dtorType), fn); 277 278 CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo); 279 280 setFunctionDefinitionAttributes(dtor, fn); 281 SetLLVMFunctionAttributesForDefinition(dtor, fn); 282 } 283 284 llvm::GlobalValue * 285 CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor, 286 CXXDtorType dtorType, 287 const CGFunctionInfo *fnInfo, 288 llvm::FunctionType *fnType, 289 bool DontDefer) { 290 GlobalDecl GD(dtor, dtorType); 291 292 StringRef name = getMangledName(GD); 293 if (llvm::GlobalValue *existing = GetGlobalValue(name)) 294 return existing; 295 296 if (!fnType) { 297 if (!fnInfo) fnInfo = &getTypes().arrangeCXXDestructor(dtor, dtorType); 298 fnType = getTypes().GetFunctionType(*fnInfo); 299 } 300 return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD, 301 /*ForVTable=*/false, 302 DontDefer)); 303 } 304 305 static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF, 306 GlobalDecl GD, 307 llvm::Type *Ty, 308 const CXXRecordDecl *RD) { 309 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() && 310 "No kext in Microsoft ABI"); 311 GD = GD.getCanonicalDecl(); 312 CodeGenModule &CGM = CGF.CGM; 313 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits()); 314 Ty = Ty->getPointerTo()->getPointerTo(); 315 VTable = CGF.Builder.CreateBitCast(VTable, Ty); 316 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null"); 317 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); 318 uint64_t AddressPoint = 319 CGM.getItaniumVTableContext().getVTableLayout(RD) 320 .getAddressPoint(BaseSubobject(RD, CharUnits::Zero())); 321 VTableIndex += AddressPoint; 322 llvm::Value *VFuncPtr = 323 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt"); 324 return CGF.Builder.CreateLoad(VFuncPtr); 325 } 326 327 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making 328 /// indirect call to virtual functions. It makes the call through indexing 329 /// into the vtable. 330 llvm::Value * 331 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 332 NestedNameSpecifier *Qual, 333 llvm::Type *Ty) { 334 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) && 335 "BuildAppleKextVirtualCall - bad Qual kind"); 336 337 const Type *QTy = Qual->getAsType(); 338 QualType T = QualType(QTy, 0); 339 const RecordType *RT = T->getAs<RecordType>(); 340 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record"); 341 const auto *RD = cast<CXXRecordDecl>(RT->getDecl()); 342 343 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) 344 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD); 345 346 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD); 347 } 348 349 /// BuildVirtualCall - This routine makes indirect vtable call for 350 /// call to virtual destructors. It returns 0 if it could not do it. 351 llvm::Value * 352 CodeGenFunction::BuildAppleKextVirtualDestructorCall( 353 const CXXDestructorDecl *DD, 354 CXXDtorType Type, 355 const CXXRecordDecl *RD) { 356 const auto *MD = cast<CXXMethodDecl>(DD); 357 // FIXME. Dtor_Base dtor is always direct!! 358 // It need be somehow inline expanded into the caller. 359 // -O does that. But need to support -O0 as well. 360 if (MD->isVirtual() && Type != Dtor_Base) { 361 // Compute the function type we're calling. 362 const CGFunctionInfo &FInfo = 363 CGM.getTypes().arrangeCXXDestructor(DD, Dtor_Complete); 364 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo); 365 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD); 366 } 367 return nullptr; 368 } 369