CGCXX.cpp revision 97a937532c24a8ea44317d4fdee26d9701a1e83c
1//===--- CGDecl.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 "CodeGenFunction.h" 17#include "CodeGenModule.h" 18#include "Mangle.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/RecordLayout.h" 21#include "clang/AST/Decl.h" 22#include "clang/AST/DeclCXX.h" 23#include "clang/AST/DeclObjC.h" 24#include "llvm/ADT/StringExtras.h" 25using namespace clang; 26using namespace CodeGen; 27 28void 29CodeGenFunction::GenerateStaticCXXBlockVarDeclInit(const VarDecl &D, 30 llvm::GlobalVariable *GV) { 31 // FIXME: This should use __cxa_guard_{acquire,release}? 32 33 assert(!getContext().getLangOptions().ThreadsafeStatics && 34 "thread safe statics are currently not supported!"); 35 36 llvm::SmallString<256> GuardVName; 37 llvm::raw_svector_ostream GuardVOut(GuardVName); 38 mangleGuardVariable(&D, getContext(), GuardVOut); 39 40 // Create the guard variable. 41 llvm::GlobalValue *GuardV = 42 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::Int64Ty, false, 43 GV->getLinkage(), 44 llvm::Constant::getNullValue(llvm::Type::Int64Ty), 45 GuardVName.c_str()); 46 47 // Load the first byte of the guard variable. 48 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::Int8Ty, 0); 49 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy), 50 "tmp"); 51 52 // Compare it against 0. 53 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::Int8Ty); 54 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool"); 55 56 llvm::BasicBlock *InitBlock = createBasicBlock("init"); 57 llvm::BasicBlock *EndBlock = createBasicBlock("init.end"); 58 59 // If the guard variable is 0, jump to the initializer code. 60 Builder.CreateCondBr(ICmp, InitBlock, EndBlock); 61 62 EmitBlock(InitBlock); 63 64 const Expr *Init = D.getInit(); 65 if (!hasAggregateLLVMType(Init->getType())) { 66 llvm::Value *V = EmitScalarExpr(Init); 67 Builder.CreateStore(V, GV, D.getType().isVolatileQualified()); 68 } else if (Init->getType()->isAnyComplexType()) { 69 EmitComplexExprIntoAddr(Init, GV, D.getType().isVolatileQualified()); 70 } else { 71 EmitAggExpr(Init, GV, D.getType().isVolatileQualified()); 72 } 73 74 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::Int8Ty, 1), 75 Builder.CreateBitCast(GuardV, PtrTy)); 76 77 EmitBlock(EndBlock); 78} 79 80RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD, 81 llvm::Value *Callee, 82 llvm::Value *This, 83 CallExpr::const_arg_iterator ArgBeg, 84 CallExpr::const_arg_iterator ArgEnd) { 85 assert(MD->isInstance() && 86 "Trying to emit a member call expr on a static method!"); 87 88 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); 89 90 CallArgList Args; 91 92 // Push the this ptr. 93 Args.push_back(std::make_pair(RValue::get(This), 94 MD->getThisType(getContext()))); 95 96 // And the rest of the call args 97 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd); 98 99 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType(); 100 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), 101 Callee, Args, MD); 102} 103 104RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) { 105 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()); 106 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 107 108 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); 109 110 if (MD->isVirtual()) { 111 ErrorUnsupported(CE, "virtual dispatch"); 112 } 113 114 const llvm::Type *Ty = 115 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 116 FPT->isVariadic()); 117 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty); 118 119 llvm::Value *This; 120 121 if (ME->isArrow()) 122 This = EmitScalarExpr(ME->getBase()); 123 else { 124 LValue BaseLV = EmitLValue(ME->getBase()); 125 This = BaseLV.getAddress(); 126 } 127 128 return EmitCXXMemberCall(MD, Callee, This, 129 CE->arg_begin(), CE->arg_end()); 130} 131 132RValue 133CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 134 const CXXMethodDecl *MD) { 135 assert(MD->isInstance() && 136 "Trying to emit a member call expr on a static method!"); 137 138 139 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); 140 const llvm::Type *Ty = 141 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 142 FPT->isVariadic()); 143 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty); 144 145 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress(); 146 147 return EmitCXXMemberCall(MD, Callee, This, 148 E->arg_begin() + 1, E->arg_end()); 149} 150 151llvm::Value *CodeGenFunction::LoadCXXThis() { 152 assert(isa<CXXMethodDecl>(CurFuncDecl) && 153 "Must be in a C++ member function decl to load 'this'"); 154 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() && 155 "Must be in a C++ member function decl to load 'this'"); 156 157 // FIXME: What if we're inside a block? 158 // ans: See how CodeGenFunction::LoadObjCSelf() uses 159 // CodeGenFunction::BlockForwardSelf() for how to do this. 160 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this"); 161} 162 163static bool 164GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths, 165 const CXXRecordDecl *ClassDecl, 166 const CXXRecordDecl *BaseClassDecl) { 167 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(), 168 e = ClassDecl->bases_end(); i != e; ++i) { 169 if (i->isVirtual()) 170 continue; 171 const CXXRecordDecl *Base = 172 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 173 if (Base == BaseClassDecl) { 174 NestedBasePaths.push_back(BaseClassDecl); 175 return true; 176 } 177 } 178 // BaseClassDecl not an immediate base of ClassDecl. 179 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(), 180 e = ClassDecl->bases_end(); i != e; ++i) { 181 if (i->isVirtual()) 182 continue; 183 const CXXRecordDecl *Base = 184 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 185 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) { 186 NestedBasePaths.push_back(Base); 187 return true; 188 } 189 } 190 return false; 191} 192 193llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue, 194 const CXXRecordDecl *ClassDecl, 195 const CXXRecordDecl *BaseClassDecl) { 196 if (ClassDecl == BaseClassDecl) 197 return BaseValue; 198 199 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 200 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths; 201 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl); 202 assert(NestedBasePaths.size() > 0 && 203 "AddressCXXOfBaseClass - inheritence path failed"); 204 NestedBasePaths.push_back(ClassDecl); 205 uint64_t Offset = 0; 206 207 // Accessing a member of the base class. Must add delata to 208 // the load of 'this'. 209 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) { 210 const CXXRecordDecl *DerivedClass = NestedBasePaths[i]; 211 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1]; 212 const ASTRecordLayout &Layout = 213 getContext().getASTRecordLayout(DerivedClass); 214 Offset += Layout.getBaseClassOffset(BaseClass) / 8; 215 } 216 llvm::Value *OffsetVal = 217 llvm::ConstantInt::get( 218 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset); 219 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr); 220 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr"); 221 QualType BTy = 222 getContext().getCanonicalType( 223 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl))); 224 const llvm::Type *BasePtr = ConvertType(BTy); 225 BasePtr = llvm::PointerType::getUnqual(BasePtr); 226 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr); 227 return BaseValue; 228} 229 230void 231CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 232 CXXCtorType Type, 233 llvm::Value *This, 234 CallExpr::const_arg_iterator ArgBeg, 235 CallExpr::const_arg_iterator ArgEnd) { 236 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); 237 238 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd); 239} 240 241void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D, 242 CXXDtorType Type, 243 llvm::Value *This) { 244 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type); 245 246 EmitCXXMemberCall(D, Callee, This, 0, 0); 247} 248 249void 250CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest, 251 const CXXConstructExpr *E) { 252 assert(Dest && "Must have a destination!"); 253 254 const CXXRecordDecl *RD = 255 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl()); 256 if (RD->hasTrivialConstructor()) 257 return; 258 259 // Code gen optimization to eliminate copy constructor and return 260 // its first argument instead. 261 if (E->isElidable()) { 262 CXXConstructExpr::const_arg_iterator i = E->arg_begin(); 263 EmitAggExpr((*i), Dest, false); 264 return; 265 } 266 // Call the constructor. 267 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest, 268 E->arg_begin(), E->arg_end()); 269} 270 271llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 272 if (E->isArray()) { 273 ErrorUnsupported(E, "new[] expression"); 274 return llvm::UndefValue::get(ConvertType(E->getType())); 275 } 276 277 QualType AllocType = E->getAllocatedType(); 278 FunctionDecl *NewFD = E->getOperatorNew(); 279 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType(); 280 281 CallArgList NewArgs; 282 283 // The allocation size is the first argument. 284 QualType SizeTy = getContext().getSizeType(); 285 llvm::Value *AllocSize = 286 llvm::ConstantInt::get(ConvertType(SizeTy), 287 getContext().getTypeSize(AllocType) / 8); 288 289 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy)); 290 291 // Emit the rest of the arguments. 292 // FIXME: Ideally, this should just use EmitCallArgs. 293 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin(); 294 295 // First, use the types from the function type. 296 // We start at 1 here because the first argument (the allocation size) 297 // has already been emitted. 298 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) { 299 QualType ArgType = NewFTy->getArgType(i); 300 301 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 302 getTypePtr() == 303 getContext().getCanonicalType(NewArg->getType()).getTypePtr() && 304 "type mismatch in call argument!"); 305 306 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType), 307 ArgType)); 308 309 } 310 311 // Either we've emitted all the call args, or we have a call to a 312 // variadic function. 313 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) && 314 "Extra arguments in non-variadic function!"); 315 316 // If we still have any arguments, emit them using the type of the argument. 317 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end(); 318 NewArg != NewArgEnd; ++NewArg) { 319 QualType ArgType = NewArg->getType(); 320 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType), 321 ArgType)); 322 } 323 324 // Emit the call to new. 325 RValue RV = 326 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs), 327 CGM.GetAddrOfFunction(GlobalDecl(NewFD)), 328 NewArgs, NewFD); 329 330 // If an allocation function is declared with an empty exception specification 331 // it returns null to indicate failure to allocate storage. [expr.new]p13. 332 // (We don't need to check for null when there's no new initializer and 333 // we're allocating a POD type). 334 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() && 335 !(AllocType->isPODType() && !E->hasInitializer()); 336 337 llvm::BasicBlock *NewNull = 0; 338 llvm::BasicBlock *NewNotNull = 0; 339 llvm::BasicBlock *NewEnd = 0; 340 341 llvm::Value *NewPtr = RV.getScalarVal(); 342 343 if (NullCheckResult) { 344 NewNull = createBasicBlock("new.null"); 345 NewNotNull = createBasicBlock("new.notnull"); 346 NewEnd = createBasicBlock("new.end"); 347 348 llvm::Value *IsNull = 349 Builder.CreateICmpEQ(NewPtr, 350 llvm::Constant::getNullValue(NewPtr->getType()), 351 "isnull"); 352 353 Builder.CreateCondBr(IsNull, NewNull, NewNotNull); 354 EmitBlock(NewNotNull); 355 } 356 357 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType())); 358 359 if (AllocType->isPODType()) { 360 if (E->getNumConstructorArgs() > 0) { 361 assert(E->getNumConstructorArgs() == 1 && 362 "Can only have one argument to initializer of POD type."); 363 364 const Expr *Init = E->getConstructorArg(0); 365 366 if (!hasAggregateLLVMType(AllocType)) 367 Builder.CreateStore(EmitScalarExpr(Init), NewPtr); 368 else if (AllocType->isAnyComplexType()) 369 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified()); 370 else 371 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified()); 372 } 373 } else { 374 // Call the constructor. 375 CXXConstructorDecl *Ctor = E->getConstructor(); 376 377 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr, 378 E->constructor_arg_begin(), 379 E->constructor_arg_end()); 380 } 381 382 if (NullCheckResult) { 383 Builder.CreateBr(NewEnd); 384 EmitBlock(NewNull); 385 Builder.CreateBr(NewEnd); 386 EmitBlock(NewEnd); 387 388 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType()); 389 PHI->reserveOperandSpace(2); 390 PHI->addIncoming(NewPtr, NewNotNull); 391 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull); 392 393 NewPtr = PHI; 394 } 395 396 return NewPtr; 397} 398 399static bool canGenerateCXXstructor(const CXXRecordDecl *RD, 400 ASTContext &Context) { 401 // The class has base classes - we don't support that right now. 402 if (RD->getNumBases() > 0) 403 return false; 404 405 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 406 I != E; ++I) { 407 // We don't support ctors for fields that aren't POD. 408 if (!I->getType()->isPODType()) 409 return false; 410 } 411 412 return true; 413} 414 415void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) { 416 if (!canGenerateCXXstructor(D->getParent(), getContext())) { 417 ErrorUnsupported(D, "C++ constructor", true); 418 return; 419 } 420 421 EmitGlobal(GlobalDecl(D, Ctor_Complete)); 422 EmitGlobal(GlobalDecl(D, Ctor_Base)); 423} 424 425void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D, 426 CXXCtorType Type) { 427 428 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type); 429 430 CodeGenFunction(*this).GenerateCode(D, Fn); 431 432 SetFunctionDefinitionAttributes(D, Fn); 433 SetLLVMFunctionAttributesForDefinition(D, Fn); 434} 435 436llvm::Function * 437CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D, 438 CXXCtorType Type) { 439 const llvm::FunctionType *FTy = 440 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false); 441 442 const char *Name = getMangledCXXCtorName(D, Type); 443 return cast<llvm::Function>( 444 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); 445} 446 447const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D, 448 CXXCtorType Type) { 449 llvm::SmallString<256> Name; 450 llvm::raw_svector_ostream Out(Name); 451 mangleCXXCtor(D, Type, Context, Out); 452 453 Name += '\0'; 454 return UniqueMangledName(Name.begin(), Name.end()); 455} 456 457void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) { 458 if (!canGenerateCXXstructor(D->getParent(), getContext())) { 459 ErrorUnsupported(D, "C++ destructor", true); 460 return; 461 } 462 463 EmitCXXDestructor(D, Dtor_Complete); 464 EmitCXXDestructor(D, Dtor_Base); 465} 466 467void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D, 468 CXXDtorType Type) { 469 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type); 470 471 CodeGenFunction(*this).GenerateCode(D, Fn); 472 473 SetFunctionDefinitionAttributes(D, Fn); 474 SetLLVMFunctionAttributesForDefinition(D, Fn); 475} 476 477llvm::Function * 478CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D, 479 CXXDtorType Type) { 480 const llvm::FunctionType *FTy = 481 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false); 482 483 const char *Name = getMangledCXXDtorName(D, Type); 484 return cast<llvm::Function>( 485 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); 486} 487 488const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D, 489 CXXDtorType Type) { 490 llvm::SmallString<256> Name; 491 llvm::raw_svector_ostream Out(Name); 492 mangleCXXDtor(D, Type, Context, Out); 493 494 Name += '\0'; 495 return UniqueMangledName(Name.begin(), Name.end()); 496} 497 498llvm::Constant *CodeGenFunction::GenerateRtti(const CXXRecordDecl *RD) { 499 llvm::Type *Ptr8Ty; 500 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0); 501 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty); 502 503 if (!getContext().getLangOptions().Rtti) 504 return Rtti; 505 506 llvm::SmallString<256> OutName; 507 llvm::raw_svector_ostream Out(OutName); 508 QualType ClassTy; 509 ClassTy = getContext().getTagDeclType(RD); 510 mangleCXXRtti(ClassTy, getContext(), Out); 511 const char *Name = OutName.c_str(); 512 llvm::GlobalVariable::LinkageTypes linktype; 513 linktype = llvm::GlobalValue::WeakAnyLinkage; 514 std::vector<llvm::Constant *> info; 515 // assert (0 && "FIXME: implement rtti descriptor"); 516 // FIXME: descriptor 517 info.push_back(llvm::Constant::getNullValue(Ptr8Ty)); 518 // assert (0 && "FIXME: implement rtti ts"); 519 // FIXME: TS 520 info.push_back(llvm::Constant::getNullValue(Ptr8Ty)); 521 522 llvm::Constant *C; 523 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size()); 524 C = llvm::ConstantArray::get(type, info); 525 Rtti = new llvm::GlobalVariable(CGM.getModule(), type, true, linktype, C, 526 Name); 527 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty); 528 return Rtti; 529} 530 531void CodeGenFunction::GenerateVtableForBase(const CXXRecordDecl *RD, 532 const CXXRecordDecl *Class, 533 llvm::Constant *rtti, 534 std::vector<llvm::Constant *> &methods, 535 bool isPrimary, 536 bool ForVirtualBase) { 537 typedef CXXRecordDecl::method_iterator meth_iter; 538 llvm::Type *Ptr8Ty; 539 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0); 540 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty); 541 542 if (RD && !RD->isDynamicClass()) 543 return; 544 545 if (RD && ForVirtualBase) 546 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 547 ++mi) { 548 if (mi->isVirtual()) { 549 // FIXME: vcall: offset for virtual base for this function 550 m = llvm::Constant::getNullValue(Ptr8Ty); 551 methods.push_back(m); 552 } 553 } 554 if (isPrimary && ForVirtualBase) 555 for (meth_iter mi = Class->method_begin(), 556 me = Class->method_end(); mi != me; ++mi) { 557 if (mi->isVirtual()) { 558 // FIXME: vcall: offset for virtual base for this function 559 m = llvm::Constant::getNullValue(Ptr8Ty); 560 methods.push_back(m); 561 } 562 } 563 564 if (RD) { 565 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Class); 566 int64_t BaseOffset = -(Layout.getBaseClassOffset(RD) / 8); 567 m = llvm::ConstantInt::get(llvm::Type::Int64Ty, BaseOffset); 568 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty); 569 } 570 methods.push_back(m); 571 methods.push_back(rtti); 572 573 if (RD) 574 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 575 ++mi) { 576 if (mi->isVirtual()) { 577 m = CGM.GetAddrOfFunction(GlobalDecl(*mi)); 578 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty); 579 methods.push_back(m); 580 } 581 } 582 if (!isPrimary) 583 return; 584 585 // And add the virtuals for the class to the primary vtable. 586 for (meth_iter mi = Class->method_begin(), me = Class->method_end(); mi != me; 587 ++mi) { 588 if (mi->isVirtual()) { 589 m = CGM.GetAddrOfFunction(GlobalDecl(*mi)); 590 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty); 591 methods.push_back(m); 592 } 593 } 594} 595 596llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) { 597 llvm::SmallString<256> OutName; 598 llvm::raw_svector_ostream Out(OutName); 599 QualType ClassTy; 600 ClassTy = getContext().getTagDeclType(RD); 601 mangleCXXVtable(ClassTy, getContext(), Out); 602 const char *Name = OutName.c_str(); 603 llvm::GlobalVariable::LinkageTypes linktype; 604 linktype = llvm::GlobalValue::WeakAnyLinkage; 605 std::vector<llvm::Constant *> methods; 606 typedef CXXRecordDecl::method_iterator meth_iter; 607 llvm::Type *Ptr8Ty; 608 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0); 609 int64_t Offset = 0; 610 llvm::Constant *rtti = GenerateRtti(RD); 611 612 Offset += LLVMPointerWidth; 613 Offset += LLVMPointerWidth; 614 615 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 616 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 617 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual(); 618 619 // The primary base comes first. 620 GenerateVtableForBase(PrimaryBase, RD, rtti, methods, true, 621 PrimaryBaseWasVirtual); 622 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 623 e = RD->bases_end(); i != e; ++i) { 624 if (i->isVirtual()) 625 continue; 626 const CXXRecordDecl *Base = 627 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 628 if (PrimaryBase != Base) { 629 GenerateVtableForBase(Base, RD, rtti, methods); 630 } 631 } 632 633 // FIXME: finish layout for virtual bases 634 // FIXME: audit indirect virtual bases 635 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(), 636 e = RD->vbases_end(); i != e; ++i) { 637 const CXXRecordDecl *Base = 638 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 639 if (Base != PrimaryBase) 640 GenerateVtableForBase(Base, RD, rtti, methods, false, true); 641 } 642 643 llvm::Constant *C; 644 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size()); 645 C = llvm::ConstantArray::get(type, methods); 646 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true, 647 linktype, C, Name); 648 vtable = Builder.CreateBitCast(vtable, Ptr8Ty); 649 vtable = Builder.CreateGEP(vtable, 650 llvm::ConstantInt::get(llvm::Type::Int64Ty, 651 Offset/8)); 652 return vtable; 653} 654 655/// EmitCopyCtorBody - This routine implicitly defines body of a copy 656/// constructor, in accordance with section 12.8 (p7 and p8) of C++03 657/// The implicitly-defined copy constructor for class X performs a memberwise 658/// copy of its subobjects. The order of copying is the same as the order 659/// of initialization of bases and members in a user-defined constructor 660/// Each subobject is copied in the manner appropriate to its type: 661/// if the subobject is of class type, the copy constructor for the class is 662/// used; 663/// if the subobject is an array, each element is copied, in the manner 664/// appropriate to the element type; 665/// if the subobject is of scalar type, the built-in assignment operator is 666/// used. 667/// Virtual base class subobjects shall be copied only once by the 668/// implicitly-defined copy constructor 669 670void CodeGenFunction::EmitCopyCtorBody(const CXXConstructorDecl *CD) { 671 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 672 assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 673 "EmitCopyCtorBody - copy constructor has definition already"); 674 675 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 676 Base != ClassDecl->bases_end(); ++Base) { 677 // FIXME. copy constrution of virtual base NYI 678 if (Base->isVirtual()) 679 continue; 680#if 0 681 unsigned TypeQuals; 682 CXXRecordDecl *BaseClassDecl 683 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 684 if (CXXConstructorDecl *BaseCopyCtor = 685 BaseClassDecl->getCopyConstructor(getContext(), TypeQuals)) { 686 687 llvm::Value *LoadOfThis = LoadCXXThis(); 688 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl, 689 BaseClassDecl); 690 EmitCXXConstructorCall(BaseCopyCtor, 691 Ctor_Complete, V, 692 Member->const_arg_begin(), 693 Member->const_arg_end()); 694 695 } 696#endif 697 } 698 699} 700 701 702/// EmitCtorPrologue - This routine generates necessary code to initialize 703/// base classes and non-static data members belonging to this constructor. 704void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) { 705 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 706 // FIXME: Add vbase initialization 707 llvm::Value *LoadOfThis = 0; 708 709 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 710 E = CD->init_end(); 711 B != E; ++B) { 712 CXXBaseOrMemberInitializer *Member = (*B); 713 if (Member->isBaseInitializer()) { 714 LoadOfThis = LoadCXXThis(); 715 Type *BaseType = Member->getBaseClass(); 716 CXXRecordDecl *BaseClassDecl = 717 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 718 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl, 719 BaseClassDecl); 720 EmitCXXConstructorCall(Member->getConstructor(), 721 Ctor_Complete, V, 722 Member->const_arg_begin(), 723 Member->const_arg_end()); 724 } else { 725 // non-static data member initilaizers. 726 FieldDecl *Field = Member->getMember(); 727 QualType FieldType = getContext().getCanonicalType((Field)->getType()); 728 assert(!getContext().getAsArrayType(FieldType) 729 && "FIXME. Field arrays initialization unsupported"); 730 731 LoadOfThis = LoadCXXThis(); 732 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0); 733 if (FieldType->getAs<RecordType>()) { 734 735 assert(Member->getConstructor() && 736 "EmitCtorPrologue - no constructor to initialize member"); 737 EmitCXXConstructorCall(Member->getConstructor(), 738 Ctor_Complete, LHS.getAddress(), 739 Member->const_arg_begin(), 740 Member->const_arg_end()); 741 continue; 742 } 743 744 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only"); 745 Expr *RhsExpr = *Member->arg_begin(); 746 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true); 747 if (LHS.isBitfield()) 748 EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, FieldType, 0); 749 else 750 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType); 751 } 752 } 753 754 // Initialize the vtable pointer 755 if (ClassDecl->isDynamicClass()) { 756 if (!LoadOfThis) 757 LoadOfThis = LoadCXXThis(); 758 llvm::Value *VtableField; 759 llvm::Type *Ptr8Ty, *PtrPtr8Ty; 760 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0); 761 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0); 762 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty); 763 llvm::Value *vtable = GenerateVtable(ClassDecl); 764 Builder.CreateStore(vtable, VtableField); 765 } 766} 767 768/// EmitDtorEpilogue - Emit all code that comes at the end of class's 769/// destructor. This is to call destructors on members and base classes 770/// in reverse order of their construction. 771void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) { 772 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext()); 773 assert(!ClassDecl->isPolymorphic() && 774 "FIXME. polymorphic destruction not supported"); 775 (void)ClassDecl; // prevent warning. 776 777 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(), 778 *E = DD->destr_end(); B != E; ++B) { 779 uintptr_t BaseOrMember = (*B); 780 if (DD->isMemberToDestroy(BaseOrMember)) { 781 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember); 782 QualType FieldType = getContext().getCanonicalType((FD)->getType()); 783 assert(!getContext().getAsArrayType(FieldType) 784 && "FIXME. Field arrays destruction unsupported"); 785 const RecordType *RT = FieldType->getAs<RecordType>(); 786 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 787 if (FieldClassDecl->hasTrivialDestructor()) 788 continue; 789 llvm::Value *LoadOfThis = LoadCXXThis(); 790 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0); 791 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()), 792 Dtor_Complete, LHS.getAddress()); 793 } else { 794 const RecordType *RT = 795 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>(); 796 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 797 if (BaseClassDecl->hasTrivialDestructor()) 798 continue; 799 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(), 800 ClassDecl,BaseClassDecl); 801 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()), 802 Dtor_Complete, V); 803 } 804 } 805} 806