CGCXX.cpp revision 566abee1e9828a7700b51e4d17ea08234fde3bb4
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 "clang/AST/StmtCXX.h" 25#include "llvm/ADT/StringExtras.h" 26using namespace clang; 27using namespace CodeGen; 28 29void 30CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn, 31 llvm::Constant *DeclPtr) { 32 const llvm::Type *Int8PtrTy = 33 llvm::Type::getInt8Ty(VMContext)->getPointerTo(); 34 35 std::vector<const llvm::Type *> Params; 36 Params.push_back(Int8PtrTy); 37 38 // Get the destructor function type 39 const llvm::Type *DtorFnTy = 40 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false); 41 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy); 42 43 Params.clear(); 44 Params.push_back(DtorFnTy); 45 Params.push_back(Int8PtrTy); 46 Params.push_back(Int8PtrTy); 47 48 // Get the __cxa_atexit function type 49 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d ); 50 const llvm::FunctionType *AtExitFnTy = 51 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false); 52 53 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy, 54 "__cxa_atexit"); 55 56 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy, 57 "__dso_handle"); 58 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy), 59 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy), 60 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) }; 61 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args)); 62} 63 64void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D, 65 llvm::Constant *DeclPtr) { 66 assert(D.hasGlobalStorage() && 67 "VarDecl must have global storage!"); 68 69 const Expr *Init = D.getInit(); 70 QualType T = D.getType(); 71 bool isVolatile = getContext().getCanonicalType(T).isVolatileQualified(); 72 73 if (T->isReferenceType()) { 74 ErrorUnsupported(Init, "global variable that binds to a reference"); 75 } else if (!hasAggregateLLVMType(T)) { 76 llvm::Value *V = EmitScalarExpr(Init); 77 EmitStoreOfScalar(V, DeclPtr, isVolatile, T); 78 } else if (T->isAnyComplexType()) { 79 EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile); 80 } else { 81 EmitAggExpr(Init, DeclPtr, isVolatile); 82 // Avoid generating destructor(s) for initialized objects. 83 if (!isa<CXXConstructExpr>(Init)) 84 return; 85 const ConstantArrayType *Array = getContext().getAsConstantArrayType(T); 86 if (Array) 87 T = getContext().getBaseElementType(Array); 88 89 if (const RecordType *RT = T->getAs<RecordType>()) { 90 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 91 if (!RD->hasTrivialDestructor()) { 92 llvm::Constant *DtorFn; 93 if (Array) { 94 DtorFn = CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper( 95 RD->getDestructor(getContext()), 96 Array, DeclPtr); 97 DeclPtr = 98 llvm::Constant::getNullValue(llvm::Type::getInt8PtrTy(VMContext)); 99 } 100 else 101 DtorFn = CGM.GetAddrOfCXXDestructor(RD->getDestructor(getContext()), 102 Dtor_Complete); 103 EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr); 104 } 105 } 106 } 107} 108 109void 110CodeGenModule::EmitCXXGlobalInitFunc() { 111 if (CXXGlobalInits.empty()) 112 return; 113 114 const llvm::FunctionType *FTy 115 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 116 false); 117 118 // Create our global initialization function. 119 // FIXME: Should this be tweakable by targets? 120 llvm::Function *Fn = 121 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage, 122 "__cxx_global_initialization", &TheModule); 123 124 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, 125 &CXXGlobalInits[0], 126 CXXGlobalInits.size()); 127 AddGlobalCtor(Fn); 128} 129 130void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn, 131 const VarDecl **Decls, 132 unsigned NumDecls) { 133 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(), 134 SourceLocation()); 135 136 for (unsigned i = 0; i != NumDecls; ++i) { 137 const VarDecl *D = Decls[i]; 138 139 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D); 140 EmitCXXGlobalVarDeclInit(*D, DeclPtr); 141 } 142 FinishFunction(); 143} 144 145void 146CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D, 147 llvm::GlobalVariable *GV) { 148 // FIXME: This should use __cxa_guard_{acquire,release}? 149 150 assert(!getContext().getLangOptions().ThreadsafeStatics && 151 "thread safe statics are currently not supported!"); 152 153 llvm::SmallString<256> GuardVName; 154 llvm::raw_svector_ostream GuardVOut(GuardVName); 155 mangleGuardVariable(CGM.getMangleContext(), &D, GuardVOut); 156 157 // Create the guard variable. 158 llvm::GlobalValue *GuardV = 159 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), 160 false, GV->getLinkage(), 161 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)), 162 GuardVName.str()); 163 164 // Load the first byte of the guard variable. 165 const llvm::Type *PtrTy 166 = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0); 167 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy), 168 "tmp"); 169 170 // Compare it against 0. 171 llvm::Value *nullValue 172 = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)); 173 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool"); 174 175 llvm::BasicBlock *InitBlock = createBasicBlock("init"); 176 llvm::BasicBlock *EndBlock = createBasicBlock("init.end"); 177 178 // If the guard variable is 0, jump to the initializer code. 179 Builder.CreateCondBr(ICmp, InitBlock, EndBlock); 180 181 EmitBlock(InitBlock); 182 183 EmitCXXGlobalVarDeclInit(D, GV); 184 185 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 186 1), 187 Builder.CreateBitCast(GuardV, PtrTy)); 188 189 EmitBlock(EndBlock); 190} 191 192RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD, 193 llvm::Value *Callee, 194 llvm::Value *This, 195 CallExpr::const_arg_iterator ArgBeg, 196 CallExpr::const_arg_iterator ArgEnd) { 197 assert(MD->isInstance() && 198 "Trying to emit a member call expr on a static method!"); 199 200 // A call to a trivial destructor requires no code generation. 201 if (const CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(MD)) 202 if (Destructor->isTrivial()) 203 return RValue::get(0); 204 205 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 206 207 CallArgList Args; 208 209 // Push the this ptr. 210 Args.push_back(std::make_pair(RValue::get(This), 211 MD->getThisType(getContext()))); 212 213 // And the rest of the call args 214 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd); 215 216 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType(); 217 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), 218 Callee, Args, MD); 219} 220 221/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 222/// expr can be devirtualized. 223static bool canDevirtualizeMemberFunctionCalls(const Expr *Base) { 224 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 225 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 226 // This is a record decl. We know the type and can devirtualize it. 227 return VD->getType()->isRecordType(); 228 } 229 230 return false; 231 } 232 233 // We can always devirtualize calls on temporary object expressions. 234 if (isa<CXXTemporaryObjectExpr>(Base)) 235 return true; 236 237 // And calls on bound temporaries. 238 if (isa<CXXBindTemporaryExpr>(Base)) 239 return true; 240 241 // Check if this is a call expr that returns a record type. 242 if (const CallExpr *CE = dyn_cast<CallExpr>(Base)) 243 return CE->getCallReturnType()->isRecordType(); 244 245 // We can't devirtualize the call. 246 return false; 247} 248 249RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) { 250 if (isa<BinaryOperator>(CE->getCallee())) 251 return EmitCXXMemberPointerCallExpr(CE); 252 253 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()); 254 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 255 256 if (MD->isStatic()) { 257 // The method is static, emit it as we would a regular call. 258 llvm::Value *Callee = CGM.GetAddrOfFunction(MD); 259 return EmitCall(Callee, getContext().getPointerType(MD->getType()), 260 CE->arg_begin(), CE->arg_end(), 0); 261 262 } 263 264 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 265 266 const llvm::Type *Ty = 267 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 268 FPT->isVariadic()); 269 llvm::Value *This; 270 271 if (ME->isArrow()) 272 This = EmitScalarExpr(ME->getBase()); 273 else { 274 LValue BaseLV = EmitLValue(ME->getBase()); 275 This = BaseLV.getAddress(); 276 } 277 278 // C++ [class.virtual]p12: 279 // Explicit qualification with the scope operator (5.1) suppresses the 280 // virtual call mechanism. 281 // 282 // We also don't emit a virtual call if the base expression has a record type 283 // because then we know what the type is. 284 llvm::Value *Callee; 285 if (MD->isVirtual() && !ME->hasQualifier() && 286 !canDevirtualizeMemberFunctionCalls(ME->getBase())) 287 Callee = BuildVirtualCall(MD, This, Ty); 288 else if (const CXXDestructorDecl *Destructor 289 = dyn_cast<CXXDestructorDecl>(MD)) 290 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty); 291 else 292 Callee = CGM.GetAddrOfFunction(MD, Ty); 293 294 return EmitCXXMemberCall(MD, Callee, This, 295 CE->arg_begin(), CE->arg_end()); 296} 297 298RValue 299CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E) { 300 const BinaryOperator *BO = cast<BinaryOperator>(E->getCallee()); 301 const Expr *BaseExpr = BO->getLHS(); 302 const Expr *MemFnExpr = BO->getRHS(); 303 304 const MemberPointerType *MPT = 305 MemFnExpr->getType()->getAs<MemberPointerType>(); 306 const FunctionProtoType *FPT = 307 MPT->getPointeeType()->getAs<FunctionProtoType>(); 308 const CXXRecordDecl *RD = 309 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 310 311 const llvm::FunctionType *FTy = 312 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT), 313 FPT->isVariadic()); 314 315 const llvm::Type *Int8PtrTy = 316 llvm::Type::getInt8Ty(VMContext)->getPointerTo(); 317 318 // Get the member function pointer. 319 llvm::Value *MemFnPtr = 320 CreateTempAlloca(ConvertType(MemFnExpr->getType()), "mem.fn"); 321 EmitAggExpr(MemFnExpr, MemFnPtr, /*VolatileDest=*/false); 322 323 // Emit the 'this' pointer. 324 llvm::Value *This; 325 326 if (BO->getOpcode() == BinaryOperator::PtrMemI) 327 This = EmitScalarExpr(BaseExpr); 328 else 329 This = EmitLValue(BaseExpr).getAddress(); 330 331 // Adjust it. 332 llvm::Value *Adj = Builder.CreateStructGEP(MemFnPtr, 1); 333 Adj = Builder.CreateLoad(Adj, "mem.fn.adj"); 334 335 llvm::Value *Ptr = Builder.CreateBitCast(This, Int8PtrTy, "ptr"); 336 Ptr = Builder.CreateGEP(Ptr, Adj, "adj"); 337 338 This = Builder.CreateBitCast(Ptr, This->getType(), "this"); 339 340 llvm::Value *FnPtr = Builder.CreateStructGEP(MemFnPtr, 0, "mem.fn.ptr"); 341 342 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType()); 343 344 llvm::Value *FnAsInt = Builder.CreateLoad(FnPtr, "fn"); 345 346 // If the LSB in the function pointer is 1, the function pointer points to 347 // a virtual function. 348 llvm::Value *IsVirtual 349 = Builder.CreateAnd(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1), 350 "and"); 351 352 IsVirtual = Builder.CreateTrunc(IsVirtual, 353 llvm::Type::getInt1Ty(VMContext)); 354 355 llvm::BasicBlock *FnVirtual = createBasicBlock("fn.virtual"); 356 llvm::BasicBlock *FnNonVirtual = createBasicBlock("fn.nonvirtual"); 357 llvm::BasicBlock *FnEnd = createBasicBlock("fn.end"); 358 359 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 360 EmitBlock(FnVirtual); 361 362 const llvm::Type *VTableTy = 363 FTy->getPointerTo()->getPointerTo()->getPointerTo(); 364 365 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy); 366 VTable = Builder.CreateLoad(VTable); 367 368 VTable = Builder.CreateGEP(VTable, FnAsInt, "fn"); 369 370 // Since the function pointer is 1 plus the virtual table offset, we 371 // subtract 1 by using a GEP. 372 VTable = Builder.CreateConstGEP1_64(VTable, (uint64_t)-1); 373 374 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "virtualfn"); 375 376 EmitBranch(FnEnd); 377 EmitBlock(FnNonVirtual); 378 379 // If the function is not virtual, just load the pointer. 380 llvm::Value *NonVirtualFn = Builder.CreateLoad(FnPtr, "fn"); 381 NonVirtualFn = Builder.CreateIntToPtr(NonVirtualFn, FTy->getPointerTo()); 382 383 EmitBlock(FnEnd); 384 385 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo()); 386 Callee->reserveOperandSpace(2); 387 Callee->addIncoming(VirtualFn, FnVirtual); 388 Callee->addIncoming(NonVirtualFn, FnNonVirtual); 389 390 CallArgList Args; 391 392 QualType ThisType = 393 getContext().getPointerType(getContext().getTagDeclType(RD)); 394 395 // Push the this ptr. 396 Args.push_back(std::make_pair(RValue::get(This), ThisType)); 397 398 // And the rest of the call args 399 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end()); 400 QualType ResultType = BO->getType()->getAs<FunctionType>()->getResultType(); 401 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), 402 Callee, Args, 0); 403} 404 405RValue 406CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 407 const CXXMethodDecl *MD) { 408 assert(MD->isInstance() && 409 "Trying to emit a member call expr on a static method!"); 410 411 if (MD->isCopyAssignment()) { 412 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext()); 413 if (ClassDecl->hasTrivialCopyAssignment()) { 414 assert(!ClassDecl->hasUserDeclaredCopyAssignment() && 415 "EmitCXXOperatorMemberCallExpr - user declared copy assignment"); 416 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress(); 417 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress(); 418 QualType Ty = E->getType(); 419 EmitAggregateCopy(This, Src, Ty); 420 return RValue::get(This); 421 } 422 } 423 424 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 425 const llvm::Type *Ty = 426 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 427 FPT->isVariadic()); 428 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, Ty); 429 430 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress(); 431 432 return EmitCXXMemberCall(MD, Callee, This, 433 E->arg_begin() + 1, E->arg_end()); 434} 435 436llvm::Value *CodeGenFunction::LoadCXXThis() { 437 assert(isa<CXXMethodDecl>(CurFuncDecl) && 438 "Must be in a C++ member function decl to load 'this'"); 439 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() && 440 "Must be in a C++ member function decl to load 'this'"); 441 442 // FIXME: What if we're inside a block? 443 // ans: See how CodeGenFunction::LoadObjCSelf() uses 444 // CodeGenFunction::BlockForwardSelf() for how to do this. 445 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this"); 446} 447 448/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested) 449/// for-loop to call the default constructor on individual members of the 450/// array. 451/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the 452/// array type and 'ArrayPtr' points to the beginning fo the array. 453/// It is assumed that all relevant checks have been made by the caller. 454void 455CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 456 const ConstantArrayType *ArrayTy, 457 llvm::Value *ArrayPtr) { 458 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 459 llvm::Value * NumElements = 460 llvm::ConstantInt::get(SizeTy, 461 getContext().getConstantArrayElementCount(ArrayTy)); 462 463 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr); 464} 465 466void 467CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 468 llvm::Value *NumElements, 469 llvm::Value *ArrayPtr) { 470 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 471 472 // Create a temporary for the loop index and initialize it with 0. 473 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index"); 474 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy); 475 Builder.CreateStore(Zero, IndexPtr, false); 476 477 // Start the loop with a block that tests the condition. 478 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 479 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 480 481 EmitBlock(CondBlock); 482 483 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 484 485 // Generate: if (loop-index < number-of-elements fall to the loop body, 486 // otherwise, go to the block after the for-loop. 487 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 488 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless"); 489 // If the condition is true, execute the body. 490 Builder.CreateCondBr(IsLess, ForBody, AfterFor); 491 492 EmitBlock(ForBody); 493 494 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 495 // Inside the loop body, emit the constructor call on the array element. 496 Counter = Builder.CreateLoad(IndexPtr); 497 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter, 498 "arrayidx"); 499 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0); 500 501 EmitBlock(ContinueBlock); 502 503 // Emit the increment of the loop counter. 504 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1); 505 Counter = Builder.CreateLoad(IndexPtr); 506 NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); 507 Builder.CreateStore(NextVal, IndexPtr, false); 508 509 // Finally, branch back up to the condition for the next iteration. 510 EmitBranch(CondBlock); 511 512 // Emit the fall-through block. 513 EmitBlock(AfterFor, true); 514} 515 516/// EmitCXXAggrDestructorCall - calls the default destructor on array 517/// elements in reverse order of construction. 518void 519CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 520 const ArrayType *Array, 521 llvm::Value *This) { 522 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array); 523 assert(CA && "Do we support VLA for destruction ?"); 524 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 525 1); 526 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA); 527 // Create a temporary for the loop index and initialize it with count of 528 // array elements. 529 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), 530 "loop.index"); 531 // Index = ElementCount; 532 llvm::Value* UpperCount = 533 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount); 534 Builder.CreateStore(UpperCount, IndexPtr, false); 535 536 // Start the loop with a block that tests the condition. 537 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 538 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 539 540 EmitBlock(CondBlock); 541 542 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 543 544 // Generate: if (loop-index != 0 fall to the loop body, 545 // otherwise, go to the block after the for-loop. 546 llvm::Value* zeroConstant = 547 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); 548 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 549 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant, 550 "isne"); 551 // If the condition is true, execute the body. 552 Builder.CreateCondBr(IsNE, ForBody, AfterFor); 553 554 EmitBlock(ForBody); 555 556 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 557 // Inside the loop body, emit the constructor call on the array element. 558 Counter = Builder.CreateLoad(IndexPtr); 559 Counter = Builder.CreateSub(Counter, One); 560 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx"); 561 EmitCXXDestructorCall(D, Dtor_Complete, Address); 562 563 EmitBlock(ContinueBlock); 564 565 // Emit the decrement of the loop counter. 566 Counter = Builder.CreateLoad(IndexPtr); 567 Counter = Builder.CreateSub(Counter, One, "dec"); 568 Builder.CreateStore(Counter, IndexPtr, false); 569 570 // Finally, branch back up to the condition for the next iteration. 571 EmitBranch(CondBlock); 572 573 // Emit the fall-through block. 574 EmitBlock(AfterFor, true); 575} 576 577/// EmitCXXAggrDestructorCall - Generates a helper function which when invoked, 578/// calls the default destructor on array elements in reverse order of 579/// construction. 580llvm::Constant * 581CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D, 582 const ArrayType *Array, 583 llvm::Value *This) { 584 static int UniqueCount; 585 FunctionArgList Args; 586 ImplicitParamDecl *Dst = 587 ImplicitParamDecl::Create(getContext(), 0, 588 SourceLocation(), 0, 589 getContext().getPointerType(getContext().VoidTy)); 590 Args.push_back(std::make_pair(Dst, Dst->getType())); 591 592 llvm::SmallString<16> Name; 593 llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueCount); 594 QualType R = getContext().VoidTy; 595 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args); 596 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false); 597 llvm::Function *Fn = 598 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage, 599 Name.c_str(), 600 &CGM.getModule()); 601 IdentifierInfo *II 602 = &CGM.getContext().Idents.get(Name.c_str()); 603 FunctionDecl *FD = FunctionDecl::Create(getContext(), 604 getContext().getTranslationUnitDecl(), 605 SourceLocation(), II, R, 0, 606 FunctionDecl::Static, 607 false, true); 608 StartFunction(FD, R, Fn, Args, SourceLocation()); 609 QualType BaseElementTy = getContext().getBaseElementType(Array); 610 const llvm::Type *BasePtr = ConvertType(BaseElementTy); 611 BasePtr = llvm::PointerType::getUnqual(BasePtr); 612 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr); 613 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr); 614 FinishFunction(); 615 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 616 0); 617 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty); 618 return m; 619} 620 621void 622CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 623 CXXCtorType Type, 624 llvm::Value *This, 625 CallExpr::const_arg_iterator ArgBeg, 626 CallExpr::const_arg_iterator ArgEnd) { 627 if (D->isCopyConstructor(getContext())) { 628 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext()); 629 if (ClassDecl->hasTrivialCopyConstructor()) { 630 assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 631 "EmitCXXConstructorCall - user declared copy constructor"); 632 const Expr *E = (*ArgBeg); 633 QualType Ty = E->getType(); 634 llvm::Value *Src = EmitLValue(E).getAddress(); 635 EmitAggregateCopy(This, Src, Ty); 636 return; 637 } 638 } 639 640 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); 641 642 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd); 643} 644 645void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D, 646 CXXDtorType Type, 647 llvm::Value *This) { 648 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type); 649 650 EmitCXXMemberCall(D, Callee, This, 0, 0); 651} 652 653void 654CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest, 655 const CXXConstructExpr *E) { 656 assert(Dest && "Must have a destination!"); 657 const CXXConstructorDecl *CD = E->getConstructor(); 658 const ConstantArrayType *Array = 659 getContext().getAsConstantArrayType(E->getType()); 660 // For a copy constructor, even if it is trivial, must fall thru so 661 // its argument is code-gen'ed. 662 if (!CD->isCopyConstructor(getContext())) { 663 QualType InitType = E->getType(); 664 if (Array) 665 InitType = getContext().getBaseElementType(Array); 666 const CXXRecordDecl *RD = 667 cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl()); 668 if (RD->hasTrivialConstructor()) 669 return; 670 } 671 // Code gen optimization to eliminate copy constructor and return 672 // its first argument instead. 673 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) { 674 const Expr *Arg = E->getArg(0); 675 676 if (const CXXBindTemporaryExpr *BindExpr = 677 dyn_cast<CXXBindTemporaryExpr>(Arg)) 678 Arg = BindExpr->getSubExpr(); 679 680 EmitAggExpr(Arg, Dest, false); 681 return; 682 } 683 if (Array) { 684 QualType BaseElementTy = getContext().getBaseElementType(Array); 685 const llvm::Type *BasePtr = ConvertType(BaseElementTy); 686 BasePtr = llvm::PointerType::getUnqual(BasePtr); 687 llvm::Value *BaseAddrPtr = 688 Builder.CreateBitCast(Dest, BasePtr); 689 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr); 690 } 691 else 692 // Call the constructor. 693 EmitCXXConstructorCall(CD, Ctor_Complete, Dest, 694 E->arg_begin(), E->arg_end()); 695} 696 697void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) { 698 EmitGlobal(GlobalDecl(D, Ctor_Complete)); 699 EmitGlobal(GlobalDecl(D, Ctor_Base)); 700} 701 702void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D, 703 CXXCtorType Type) { 704 705 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type); 706 707 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn); 708 709 SetFunctionDefinitionAttributes(D, Fn); 710 SetLLVMFunctionAttributesForDefinition(D, Fn); 711} 712 713llvm::Function * 714CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D, 715 CXXCtorType Type) { 716 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>(); 717 const llvm::FunctionType *FTy = 718 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), 719 FPT->isVariadic()); 720 721 const char *Name = getMangledCXXCtorName(D, Type); 722 return cast<llvm::Function>( 723 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); 724} 725 726const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D, 727 CXXCtorType Type) { 728 llvm::SmallString<256> Name; 729 llvm::raw_svector_ostream Out(Name); 730 mangleCXXCtor(getMangleContext(), D, Type, Out); 731 732 Name += '\0'; 733 return UniqueMangledName(Name.begin(), Name.end()); 734} 735 736void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) { 737 EmitCXXDestructor(D, Dtor_Complete); 738 EmitCXXDestructor(D, Dtor_Base); 739} 740 741void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D, 742 CXXDtorType Type) { 743 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type); 744 745 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn); 746 747 SetFunctionDefinitionAttributes(D, Fn); 748 SetLLVMFunctionAttributesForDefinition(D, Fn); 749} 750 751llvm::Function * 752CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D, 753 CXXDtorType Type) { 754 const llvm::FunctionType *FTy = 755 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false); 756 757 const char *Name = getMangledCXXDtorName(D, Type); 758 return cast<llvm::Function>( 759 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); 760} 761 762const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D, 763 CXXDtorType Type) { 764 llvm::SmallString<256> Name; 765 llvm::raw_svector_ostream Out(Name); 766 mangleCXXDtor(getMangleContext(), D, Type, Out); 767 768 Name += '\0'; 769 return UniqueMangledName(Name.begin(), Name.end()); 770} 771 772llvm::Constant *CodeGenFunction::GenerateThunk(llvm::Function *Fn, 773 const CXXMethodDecl *MD, 774 bool Extern, int64_t nv, 775 int64_t v) { 776 return GenerateCovariantThunk(Fn, MD, Extern, nv, v, 0, 0); 777} 778 779llvm::Value *CodeGenFunction::DynamicTypeAdjust(llvm::Value *V, int64_t nv, 780 int64_t v) { 781 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 782 0); 783 const llvm::Type *OrigTy = V->getType(); 784 if (nv) { 785 // Do the non-virtual adjustment 786 V = Builder.CreateBitCast(V, Ptr8Ty); 787 V = Builder.CreateConstInBoundsGEP1_64(V, nv); 788 V = Builder.CreateBitCast(V, OrigTy); 789 } 790 if (v) { 791 // Do the virtual this adjustment 792 const llvm::Type *PtrDiffTy = 793 ConvertType(getContext().getPointerDiffType()); 794 llvm::Type *PtrPtr8Ty, *PtrPtrDiffTy; 795 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0); 796 PtrPtrDiffTy = llvm::PointerType::get(PtrDiffTy, 0); 797 llvm::Value *ThisVal = Builder.CreateBitCast(V, Ptr8Ty); 798 V = Builder.CreateBitCast(V, PtrPtrDiffTy->getPointerTo()); 799 V = Builder.CreateLoad(V, "vtable"); 800 llvm::Value *VTablePtr = V; 801 assert(v % (LLVMPointerWidth/8) == 0 && "vtable entry unaligned"); 802 v /= LLVMPointerWidth/8; 803 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, v); 804 V = Builder.CreateLoad(V); 805 V = Builder.CreateGEP(ThisVal, V); 806 V = Builder.CreateBitCast(V, OrigTy); 807 } 808 return V; 809} 810 811llvm::Constant *CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn, 812 const CXXMethodDecl *MD, 813 bool Extern, 814 int64_t nv_t, 815 int64_t v_t, 816 int64_t nv_r, 817 int64_t v_r) { 818 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType(); 819 820 FunctionArgList Args; 821 ImplicitParamDecl *ThisDecl = 822 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0, 823 MD->getThisType(getContext())); 824 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType())); 825 for (FunctionDecl::param_const_iterator i = MD->param_begin(), 826 e = MD->param_end(); 827 i != e; ++i) { 828 ParmVarDecl *D = *i; 829 Args.push_back(std::make_pair(D, D->getType())); 830 } 831 IdentifierInfo *II 832 = &CGM.getContext().Idents.get("__thunk_named_foo_"); 833 FunctionDecl *FD = FunctionDecl::Create(getContext(), 834 getContext().getTranslationUnitDecl(), 835 SourceLocation(), II, ResultType, 0, 836 Extern 837 ? FunctionDecl::Extern 838 : FunctionDecl::Static, 839 false, true); 840 StartFunction(FD, ResultType, Fn, Args, SourceLocation()); 841 842 // generate body 843 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 844 const llvm::Type *Ty = 845 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 846 FPT->isVariadic()); 847 llvm::Value *Callee = CGM.GetAddrOfFunction(MD, Ty); 848 CallArgList CallArgs; 849 850 QualType ArgType = MD->getThisType(getContext()); 851 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this"); 852 if (nv_t || v_t) { 853 // Do the this adjustment. 854 const llvm::Type *OrigTy = Callee->getType(); 855 Arg = DynamicTypeAdjust(Arg, nv_t, v_t); 856 if (nv_r || v_r) { 857 Callee = CGM.BuildCovariantThunk(MD, Extern, 0, 0, nv_r, v_r); 858 Callee = Builder.CreateBitCast(Callee, OrigTy); 859 nv_r = v_r = 0; 860 } 861 } 862 863 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType)); 864 865 for (FunctionDecl::param_const_iterator i = MD->param_begin(), 866 e = MD->param_end(); 867 i != e; ++i) { 868 ParmVarDecl *D = *i; 869 QualType ArgType = D->getType(); 870 871 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst); 872 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType, SourceLocation()); 873 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType)); 874 } 875 876 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 877 Callee, CallArgs, MD); 878 if (nv_r || v_r) { 879 bool CanBeZero = !(ResultType->isReferenceType() 880 // FIXME: attr nonnull can't be zero either 881 /* || ResultType->hasAttr<NonNullAttr>() */ ); 882 // Do the return result adjustment. 883 if (CanBeZero) { 884 llvm::BasicBlock *NonZeroBlock = createBasicBlock(); 885 llvm::BasicBlock *ZeroBlock = createBasicBlock(); 886 llvm::BasicBlock *ContBlock = createBasicBlock(); 887 888 const llvm::Type *Ty = RV.getScalarVal()->getType(); 889 llvm::Value *Zero = llvm::Constant::getNullValue(Ty); 890 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero), 891 NonZeroBlock, ZeroBlock); 892 EmitBlock(NonZeroBlock); 893 llvm::Value *NZ = DynamicTypeAdjust(RV.getScalarVal(), nv_r, v_r); 894 EmitBranch(ContBlock); 895 EmitBlock(ZeroBlock); 896 llvm::Value *Z = RV.getScalarVal(); 897 EmitBlock(ContBlock); 898 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty); 899 RVOrZero->reserveOperandSpace(2); 900 RVOrZero->addIncoming(NZ, NonZeroBlock); 901 RVOrZero->addIncoming(Z, ZeroBlock); 902 RV = RValue::get(RVOrZero); 903 } else 904 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(), nv_r, v_r)); 905 } 906 907 if (!ResultType->isVoidType()) 908 EmitReturnOfRValue(RV, ResultType); 909 910 FinishFunction(); 911 return Fn; 912} 913 914llvm::Constant *CodeGenModule::BuildThunk(const CXXMethodDecl *MD, bool Extern, 915 int64_t nv, int64_t v) { 916 llvm::SmallString<256> OutName; 917 llvm::raw_svector_ostream Out(OutName); 918 mangleThunk(getMangleContext(), MD, nv, v, Out); 919 llvm::GlobalVariable::LinkageTypes linktype; 920 linktype = llvm::GlobalValue::WeakAnyLinkage; 921 if (!Extern) 922 linktype = llvm::GlobalValue::InternalLinkage; 923 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0); 924 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 925 const llvm::FunctionType *FTy = 926 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), 927 FPT->isVariadic()); 928 929 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, Out.str(), 930 &getModule()); 931 CodeGenFunction(*this).GenerateThunk(Fn, MD, Extern, nv, v); 932 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty); 933 return m; 934} 935 936llvm::Constant *CodeGenModule::BuildCovariantThunk(const CXXMethodDecl *MD, 937 bool Extern, int64_t nv_t, 938 int64_t v_t, int64_t nv_r, 939 int64_t v_r) { 940 llvm::SmallString<256> OutName; 941 llvm::raw_svector_ostream Out(OutName); 942 mangleCovariantThunk(getMangleContext(), MD, nv_t, v_t, nv_r, v_r, Out); 943 llvm::GlobalVariable::LinkageTypes linktype; 944 linktype = llvm::GlobalValue::WeakAnyLinkage; 945 if (!Extern) 946 linktype = llvm::GlobalValue::InternalLinkage; 947 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0); 948 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 949 const llvm::FunctionType *FTy = 950 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), 951 FPT->isVariadic()); 952 953 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, Out.str(), 954 &getModule()); 955 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, nv_t, v_t, nv_r, 956 v_r); 957 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty); 958 return m; 959} 960 961llvm::Value * 962CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This, 963 const CXXRecordDecl *ClassDecl, 964 const CXXRecordDecl *BaseClassDecl) { 965 const llvm::Type *Int8PtrTy = 966 llvm::Type::getInt8Ty(VMContext)->getPointerTo(); 967 968 llvm::Value *VTablePtr = Builder.CreateBitCast(This, 969 Int8PtrTy->getPointerTo()); 970 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable"); 971 972 int64_t VBaseOffsetIndex = 973 CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl); 974 975 llvm::Value *VBaseOffsetPtr = 976 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr"); 977 const llvm::Type *PtrDiffTy = 978 ConvertType(getContext().getPointerDiffType()); 979 980 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr, 981 PtrDiffTy->getPointerTo()); 982 983 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 984 985 return VBaseOffset; 986} 987 988static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, int64_t VtableIndex, 989 llvm::Value *This, const llvm::Type *Ty) { 990 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo(); 991 992 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty); 993 Vtable = CGF.Builder.CreateLoad(Vtable); 994 995 llvm::Value *VFuncPtr = 996 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn"); 997 return CGF.Builder.CreateLoad(VFuncPtr); 998} 999 1000llvm::Value * 1001CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This, 1002 const llvm::Type *Ty) { 1003 MD = MD->getCanonicalDecl(); 1004 int64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD); 1005 1006 return ::BuildVirtualCall(*this, VtableIndex, This, Ty); 1007} 1008 1009llvm::Value * 1010CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type, 1011 llvm::Value *&This, const llvm::Type *Ty) { 1012 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl()); 1013 int64_t VtableIndex = 1014 CGM.getVtableInfo().getMethodVtableIndex(DD); 1015 1016 return ::BuildVirtualCall(*this, VtableIndex, This, Ty); 1017} 1018 1019/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class 1020/// array of objects from SrcValue to DestValue. Copying can be either a bitwise 1021/// copy or via a copy constructor call. 1022// FIXME. Consolidate this with EmitCXXAggrConstructorCall. 1023void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest, 1024 llvm::Value *Src, 1025 const ArrayType *Array, 1026 const CXXRecordDecl *BaseClassDecl, 1027 QualType Ty) { 1028 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array); 1029 assert(CA && "VLA cannot be copied over"); 1030 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor(); 1031 1032 // Create a temporary for the loop index and initialize it with 0. 1033 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), 1034 "loop.index"); 1035 llvm::Value* zeroConstant = 1036 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); 1037 Builder.CreateStore(zeroConstant, IndexPtr, false); 1038 // Start the loop with a block that tests the condition. 1039 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 1040 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 1041 1042 EmitBlock(CondBlock); 1043 1044 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1045 // Generate: if (loop-index < number-of-elements fall to the loop body, 1046 // otherwise, go to the block after the for-loop. 1047 uint64_t NumElements = getContext().getConstantArrayElementCount(CA); 1048 llvm::Value * NumElementsPtr = 1049 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements); 1050 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 1051 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, 1052 "isless"); 1053 // If the condition is true, execute the body. 1054 Builder.CreateCondBr(IsLess, ForBody, AfterFor); 1055 1056 EmitBlock(ForBody); 1057 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 1058 // Inside the loop body, emit the constructor call on the array element. 1059 Counter = Builder.CreateLoad(IndexPtr); 1060 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress"); 1061 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress"); 1062 if (BitwiseCopy) 1063 EmitAggregateCopy(Dest, Src, Ty); 1064 else if (CXXConstructorDecl *BaseCopyCtor = 1065 BaseClassDecl->getCopyConstructor(getContext(), 0)) { 1066 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, 1067 Ctor_Complete); 1068 CallArgList CallArgs; 1069 // Push the this (Dest) ptr. 1070 CallArgs.push_back(std::make_pair(RValue::get(Dest), 1071 BaseCopyCtor->getThisType(getContext()))); 1072 1073 // Push the Src ptr. 1074 CallArgs.push_back(std::make_pair(RValue::get(Src), 1075 BaseCopyCtor->getParamDecl(0)->getType())); 1076 QualType ResultType = 1077 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType(); 1078 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 1079 Callee, CallArgs, BaseCopyCtor); 1080 } 1081 EmitBlock(ContinueBlock); 1082 1083 // Emit the increment of the loop counter. 1084 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); 1085 Counter = Builder.CreateLoad(IndexPtr); 1086 NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); 1087 Builder.CreateStore(NextVal, IndexPtr, false); 1088 1089 // Finally, branch back up to the condition for the next iteration. 1090 EmitBranch(CondBlock); 1091 1092 // Emit the fall-through block. 1093 EmitBlock(AfterFor, true); 1094} 1095 1096/// EmitClassAggrCopyAssignment - This routine generates code to assign a class 1097/// array of objects from SrcValue to DestValue. Assignment can be either a 1098/// bitwise assignment or via a copy assignment operator function call. 1099/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy 1100void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest, 1101 llvm::Value *Src, 1102 const ArrayType *Array, 1103 const CXXRecordDecl *BaseClassDecl, 1104 QualType Ty) { 1105 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array); 1106 assert(CA && "VLA cannot be asssigned"); 1107 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment(); 1108 1109 // Create a temporary for the loop index and initialize it with 0. 1110 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), 1111 "loop.index"); 1112 llvm::Value* zeroConstant = 1113 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); 1114 Builder.CreateStore(zeroConstant, IndexPtr, false); 1115 // Start the loop with a block that tests the condition. 1116 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 1117 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 1118 1119 EmitBlock(CondBlock); 1120 1121 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1122 // Generate: if (loop-index < number-of-elements fall to the loop body, 1123 // otherwise, go to the block after the for-loop. 1124 uint64_t NumElements = getContext().getConstantArrayElementCount(CA); 1125 llvm::Value * NumElementsPtr = 1126 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements); 1127 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 1128 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, 1129 "isless"); 1130 // If the condition is true, execute the body. 1131 Builder.CreateCondBr(IsLess, ForBody, AfterFor); 1132 1133 EmitBlock(ForBody); 1134 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 1135 // Inside the loop body, emit the assignment operator call on array element. 1136 Counter = Builder.CreateLoad(IndexPtr); 1137 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress"); 1138 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress"); 1139 const CXXMethodDecl *MD = 0; 1140 if (BitwiseAssign) 1141 EmitAggregateCopy(Dest, Src, Ty); 1142 else { 1143 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(), 1144 MD); 1145 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign"); 1146 (void)hasCopyAssign; 1147 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1148 const llvm::Type *LTy = 1149 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 1150 FPT->isVariadic()); 1151 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy); 1152 1153 CallArgList CallArgs; 1154 // Push the this (Dest) ptr. 1155 CallArgs.push_back(std::make_pair(RValue::get(Dest), 1156 MD->getThisType(getContext()))); 1157 1158 // Push the Src ptr. 1159 CallArgs.push_back(std::make_pair(RValue::get(Src), 1160 MD->getParamDecl(0)->getType())); 1161 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType(); 1162 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 1163 Callee, CallArgs, MD); 1164 } 1165 EmitBlock(ContinueBlock); 1166 1167 // Emit the increment of the loop counter. 1168 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); 1169 Counter = Builder.CreateLoad(IndexPtr); 1170 NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); 1171 Builder.CreateStore(NextVal, IndexPtr, false); 1172 1173 // Finally, branch back up to the condition for the next iteration. 1174 EmitBranch(CondBlock); 1175 1176 // Emit the fall-through block. 1177 EmitBlock(AfterFor, true); 1178} 1179 1180/// EmitClassMemberwiseCopy - This routine generates code to copy a class 1181/// object from SrcValue to DestValue. Copying can be either a bitwise copy 1182/// or via a copy constructor call. 1183void CodeGenFunction::EmitClassMemberwiseCopy( 1184 llvm::Value *Dest, llvm::Value *Src, 1185 const CXXRecordDecl *ClassDecl, 1186 const CXXRecordDecl *BaseClassDecl, QualType Ty) { 1187 if (ClassDecl) { 1188 Dest = GetAddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl, 1189 /*NullCheckValue=*/false); 1190 Src = GetAddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl, 1191 /*NullCheckValue=*/false); 1192 } 1193 if (BaseClassDecl->hasTrivialCopyConstructor()) { 1194 EmitAggregateCopy(Dest, Src, Ty); 1195 return; 1196 } 1197 1198 if (CXXConstructorDecl *BaseCopyCtor = 1199 BaseClassDecl->getCopyConstructor(getContext(), 0)) { 1200 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, 1201 Ctor_Complete); 1202 CallArgList CallArgs; 1203 // Push the this (Dest) ptr. 1204 CallArgs.push_back(std::make_pair(RValue::get(Dest), 1205 BaseCopyCtor->getThisType(getContext()))); 1206 1207 // Push the Src ptr. 1208 CallArgs.push_back(std::make_pair(RValue::get(Src), 1209 BaseCopyCtor->getParamDecl(0)->getType())); 1210 QualType ResultType = 1211 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType(); 1212 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 1213 Callee, CallArgs, BaseCopyCtor); 1214 } 1215} 1216 1217/// EmitClassCopyAssignment - This routine generates code to copy assign a class 1218/// object from SrcValue to DestValue. Assignment can be either a bitwise 1219/// assignment of via an assignment operator call. 1220// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot. 1221void CodeGenFunction::EmitClassCopyAssignment( 1222 llvm::Value *Dest, llvm::Value *Src, 1223 const CXXRecordDecl *ClassDecl, 1224 const CXXRecordDecl *BaseClassDecl, 1225 QualType Ty) { 1226 if (ClassDecl) { 1227 Dest = GetAddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl, 1228 /*NullCheckValue=*/false); 1229 Src = GetAddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl, 1230 /*NullCheckValue=*/false); 1231 } 1232 if (BaseClassDecl->hasTrivialCopyAssignment()) { 1233 EmitAggregateCopy(Dest, Src, Ty); 1234 return; 1235 } 1236 1237 const CXXMethodDecl *MD = 0; 1238 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(), 1239 MD); 1240 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign"); 1241 (void)ConstCopyAssignOp; 1242 1243 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1244 const llvm::Type *LTy = 1245 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 1246 FPT->isVariadic()); 1247 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy); 1248 1249 CallArgList CallArgs; 1250 // Push the this (Dest) ptr. 1251 CallArgs.push_back(std::make_pair(RValue::get(Dest), 1252 MD->getThisType(getContext()))); 1253 1254 // Push the Src ptr. 1255 CallArgs.push_back(std::make_pair(RValue::get(Src), 1256 MD->getParamDecl(0)->getType())); 1257 QualType ResultType = 1258 MD->getType()->getAs<FunctionType>()->getResultType(); 1259 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 1260 Callee, CallArgs, MD); 1261} 1262 1263/// SynthesizeDefaultConstructor - synthesize a default constructor 1264void 1265CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor, 1266 CXXCtorType Type, 1267 llvm::Function *Fn, 1268 const FunctionArgList &Args) { 1269 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args, 1270 SourceLocation()); 1271 EmitCtorPrologue(Ctor, Type); 1272 FinishFunction(); 1273} 1274 1275/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a 1276/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03 1277/// The implicitly-defined copy constructor for class X performs a memberwise 1278/// copy of its subobjects. The order of copying is the same as the order of 1279/// initialization of bases and members in a user-defined constructor 1280/// Each subobject is copied in the manner appropriate to its type: 1281/// if the subobject is of class type, the copy constructor for the class is 1282/// used; 1283/// if the subobject is an array, each element is copied, in the manner 1284/// appropriate to the element type; 1285/// if the subobject is of scalar type, the built-in assignment operator is 1286/// used. 1287/// Virtual base class subobjects shall be copied only once by the 1288/// implicitly-defined copy constructor 1289 1290void 1291CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor, 1292 CXXCtorType Type, 1293 llvm::Function *Fn, 1294 const FunctionArgList &Args) { 1295 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 1296 assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 1297 "SynthesizeCXXCopyConstructor - copy constructor has definition already"); 1298 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args, 1299 SourceLocation()); 1300 1301 FunctionArgList::const_iterator i = Args.begin(); 1302 const VarDecl *ThisArg = i->first; 1303 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg); 1304 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this"); 1305 const VarDecl *SrcArg = (i+1)->first; 1306 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg); 1307 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj); 1308 1309 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 1310 Base != ClassDecl->bases_end(); ++Base) { 1311 // FIXME. copy constrution of virtual base NYI 1312 if (Base->isVirtual()) 1313 continue; 1314 1315 CXXRecordDecl *BaseClassDecl 1316 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1317 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl, 1318 Base->getType()); 1319 } 1320 1321 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1322 FieldEnd = ClassDecl->field_end(); 1323 Field != FieldEnd; ++Field) { 1324 QualType FieldType = getContext().getCanonicalType((*Field)->getType()); 1325 const ConstantArrayType *Array = 1326 getContext().getAsConstantArrayType(FieldType); 1327 if (Array) 1328 FieldType = getContext().getBaseElementType(FieldType); 1329 1330 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1331 CXXRecordDecl *FieldClassDecl 1332 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1333 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0); 1334 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0); 1335 if (Array) { 1336 const llvm::Type *BasePtr = ConvertType(FieldType); 1337 BasePtr = llvm::PointerType::getUnqual(BasePtr); 1338 llvm::Value *DestBaseAddrPtr = 1339 Builder.CreateBitCast(LHS.getAddress(), BasePtr); 1340 llvm::Value *SrcBaseAddrPtr = 1341 Builder.CreateBitCast(RHS.getAddress(), BasePtr); 1342 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array, 1343 FieldClassDecl, FieldType); 1344 } 1345 else 1346 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(), 1347 0 /*ClassDecl*/, FieldClassDecl, FieldType); 1348 continue; 1349 } 1350 // Do a built-in assignment of scalar data members. 1351 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0); 1352 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0); 1353 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType); 1354 EmitStoreThroughLValue(RVRHS, LHS, FieldType); 1355 } 1356 FinishFunction(); 1357} 1358 1359/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator. 1360/// Before the implicitly-declared copy assignment operator for a class is 1361/// implicitly defined, all implicitly- declared copy assignment operators for 1362/// its direct base classes and its nonstatic data members shall have been 1363/// implicitly defined. [12.8-p12] 1364/// The implicitly-defined copy assignment operator for class X performs 1365/// memberwise assignment of its subob- jects. The direct base classes of X are 1366/// assigned first, in the order of their declaration in 1367/// the base-specifier-list, and then the immediate nonstatic data members of X 1368/// are assigned, in the order in which they were declared in the class 1369/// definition.Each subobject is assigned in the manner appropriate to its type: 1370/// if the subobject is of class type, the copy assignment operator for the 1371/// class is used (as if by explicit qualification; that is, ignoring any 1372/// possible virtual overriding functions in more derived classes); 1373/// 1374/// if the subobject is an array, each element is assigned, in the manner 1375/// appropriate to the element type; 1376/// 1377/// if the subobject is of scalar type, the built-in assignment operator is 1378/// used. 1379void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD, 1380 llvm::Function *Fn, 1381 const FunctionArgList &Args) { 1382 1383 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 1384 assert(!ClassDecl->hasUserDeclaredCopyAssignment() && 1385 "SynthesizeCXXCopyAssignment - copy assignment has user declaration"); 1386 StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation()); 1387 1388 FunctionArgList::const_iterator i = Args.begin(); 1389 const VarDecl *ThisArg = i->first; 1390 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg); 1391 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this"); 1392 const VarDecl *SrcArg = (i+1)->first; 1393 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg); 1394 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj); 1395 1396 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 1397 Base != ClassDecl->bases_end(); ++Base) { 1398 // FIXME. copy assignment of virtual base NYI 1399 if (Base->isVirtual()) 1400 continue; 1401 1402 CXXRecordDecl *BaseClassDecl 1403 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1404 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl, 1405 Base->getType()); 1406 } 1407 1408 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1409 FieldEnd = ClassDecl->field_end(); 1410 Field != FieldEnd; ++Field) { 1411 QualType FieldType = getContext().getCanonicalType((*Field)->getType()); 1412 const ConstantArrayType *Array = 1413 getContext().getAsConstantArrayType(FieldType); 1414 if (Array) 1415 FieldType = getContext().getBaseElementType(FieldType); 1416 1417 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1418 CXXRecordDecl *FieldClassDecl 1419 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1420 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0); 1421 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0); 1422 if (Array) { 1423 const llvm::Type *BasePtr = ConvertType(FieldType); 1424 BasePtr = llvm::PointerType::getUnqual(BasePtr); 1425 llvm::Value *DestBaseAddrPtr = 1426 Builder.CreateBitCast(LHS.getAddress(), BasePtr); 1427 llvm::Value *SrcBaseAddrPtr = 1428 Builder.CreateBitCast(RHS.getAddress(), BasePtr); 1429 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array, 1430 FieldClassDecl, FieldType); 1431 } 1432 else 1433 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(), 1434 0 /*ClassDecl*/, FieldClassDecl, FieldType); 1435 continue; 1436 } 1437 // Do a built-in assignment of scalar data members. 1438 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0); 1439 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0); 1440 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType); 1441 EmitStoreThroughLValue(RVRHS, LHS, FieldType); 1442 } 1443 1444 // return *this; 1445 Builder.CreateStore(LoadOfThis, ReturnValue); 1446 1447 FinishFunction(); 1448} 1449 1450static void EmitBaseInitializer(CodeGenFunction &CGF, 1451 const CXXRecordDecl *ClassDecl, 1452 CXXBaseOrMemberInitializer *BaseInit, 1453 CXXCtorType CtorType) { 1454 assert(BaseInit->isBaseInitializer() && 1455 "Must have base initializer!"); 1456 1457 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 1458 1459 const Type *BaseType = BaseInit->getBaseClass(); 1460 CXXRecordDecl *BaseClassDecl = 1461 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 1462 llvm::Value *V = CGF.GetAddressCXXOfBaseClass(ThisPtr, ClassDecl, 1463 BaseClassDecl, 1464 /*NullCheckValue=*/false); 1465 CGF.EmitCXXConstructorCall(BaseInit->getConstructor(), 1466 CtorType, V, 1467 BaseInit->const_arg_begin(), 1468 BaseInit->const_arg_end()); 1469} 1470 1471static void EmitMemberInitializer(CodeGenFunction &CGF, 1472 const CXXRecordDecl *ClassDecl, 1473 CXXBaseOrMemberInitializer *MemberInit) { 1474 assert(MemberInit->isMemberInitializer() && 1475 "Must have member initializer!"); 1476 1477 // non-static data member initializers. 1478 FieldDecl *Field = MemberInit->getMember(); 1479 QualType FieldType = CGF.getContext().getCanonicalType((Field)->getType()); 1480 const ConstantArrayType *Array = 1481 CGF.getContext().getAsConstantArrayType(FieldType); 1482 if (Array) 1483 FieldType = CGF.getContext().getBaseElementType(FieldType); 1484 1485 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 1486 LValue LHS; 1487 if (FieldType->isReferenceType()) { 1488 // FIXME: This is really ugly; should be refactored somehow 1489 unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field); 1490 llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp"); 1491 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs"); 1492 LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType)); 1493 } else { 1494 LHS = CGF.EmitLValueForField(ThisPtr, Field, false, 0); 1495 } 1496 if (FieldType->getAs<RecordType>()) { 1497 if (!Field->isAnonymousStructOrUnion()) { 1498 assert(MemberInit->getConstructor() && 1499 "EmitCtorPrologue - no constructor to initialize member"); 1500 if (Array) { 1501 const llvm::Type *BasePtr = CGF.ConvertType(FieldType); 1502 BasePtr = llvm::PointerType::getUnqual(BasePtr); 1503 llvm::Value *BaseAddrPtr = 1504 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr); 1505 CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(), 1506 Array, BaseAddrPtr); 1507 } 1508 else 1509 CGF.EmitCXXConstructorCall(MemberInit->getConstructor(), 1510 Ctor_Complete, LHS.getAddress(), 1511 MemberInit->const_arg_begin(), 1512 MemberInit->const_arg_end()); 1513 return; 1514 } 1515 else { 1516 // Initializing an anonymous union data member. 1517 FieldDecl *anonMember = MemberInit->getAnonUnionMember(); 1518 LHS = CGF.EmitLValueForField(LHS.getAddress(), anonMember, 1519 /*IsUnion=*/true, 0); 1520 FieldType = anonMember->getType(); 1521 } 1522 } 1523 1524 assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only"); 1525 Expr *RhsExpr = *MemberInit->arg_begin(); 1526 RValue RHS; 1527 if (FieldType->isReferenceType()) 1528 RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType, 1529 /*IsInitializer=*/true); 1530 else if (FieldType->isMemberFunctionPointerType()) 1531 RHS = RValue::get(CGF.CGM.EmitConstantExpr(RhsExpr, FieldType, &CGF)); 1532 else 1533 RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true)); 1534 if (Array && !FieldType->getAs<RecordType>()) { 1535 // value initialize a non-class array data member using arr() syntax in 1536 // initializer list. 1537 QualType Ty = CGF.getContext().getCanonicalType((Field)->getType()); 1538 CGF.EmitMemSetToZero(LHS.getAddress(), Ty); 1539 } 1540 else 1541 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType); 1542} 1543 1544/// EmitCtorPrologue - This routine generates necessary code to initialize 1545/// base classes and non-static data members belonging to this constructor. 1546/// FIXME: This needs to take a CXXCtorType. 1547void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 1548 CXXCtorType CtorType) { 1549 const CXXRecordDecl *ClassDecl = CD->getParent(); 1550 1551 // FIXME: Add vbase initialization 1552 llvm::Value *LoadOfThis = 0; 1553 1554 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 1555 E = CD->init_end(); 1556 B != E; ++B) { 1557 CXXBaseOrMemberInitializer *Member = (*B); 1558 1559 assert(LiveTemporaries.empty() && 1560 "Should not have any live temporaries at initializer start!"); 1561 1562 if (Member->isBaseInitializer()) 1563 EmitBaseInitializer(*this, ClassDecl, Member, CtorType); 1564 else 1565 EmitMemberInitializer(*this, ClassDecl, Member); 1566 1567 // Pop any live temporaries that the initializers might have pushed. 1568 while (!LiveTemporaries.empty()) 1569 PopCXXTemporary(); 1570 } 1571 1572 // Initialize the vtable pointer 1573 if (ClassDecl->isDynamicClass()) { 1574 if (!LoadOfThis) 1575 LoadOfThis = LoadCXXThis(); 1576 llvm::Value *VtableField; 1577 llvm::Type *Ptr8Ty, *PtrPtr8Ty; 1578 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0); 1579 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0); 1580 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty); 1581 llvm::Value *vtable = CGM.getVtableInfo().getVtable(ClassDecl); 1582 Builder.CreateStore(vtable, VtableField); 1583 } 1584} 1585 1586/// EmitDtorEpilogue - Emit all code that comes at the end of class's 1587/// destructor. This is to call destructors on members and base classes 1588/// in reverse order of their construction. 1589/// FIXME: This needs to take a CXXDtorType. 1590void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD, 1591 CXXDtorType DtorType) { 1592 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext()); 1593 assert(!ClassDecl->getNumVBases() && 1594 "FIXME: Destruction of virtual bases not supported"); 1595 (void)ClassDecl; // prevent warning. 1596 1597 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(), 1598 *E = DD->destr_end(); B != E; ++B) { 1599 uintptr_t BaseOrMember = (*B); 1600 if (DD->isMemberToDestroy(BaseOrMember)) { 1601 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember); 1602 QualType FieldType = getContext().getCanonicalType((FD)->getType()); 1603 const ConstantArrayType *Array = 1604 getContext().getAsConstantArrayType(FieldType); 1605 if (Array) 1606 FieldType = getContext().getBaseElementType(FieldType); 1607 const RecordType *RT = FieldType->getAs<RecordType>(); 1608 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1609 if (FieldClassDecl->hasTrivialDestructor()) 1610 continue; 1611 llvm::Value *LoadOfThis = LoadCXXThis(); 1612 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0); 1613 if (Array) { 1614 const llvm::Type *BasePtr = ConvertType(FieldType); 1615 BasePtr = llvm::PointerType::getUnqual(BasePtr); 1616 llvm::Value *BaseAddrPtr = 1617 Builder.CreateBitCast(LHS.getAddress(), BasePtr); 1618 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()), 1619 Array, BaseAddrPtr); 1620 } 1621 else 1622 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()), 1623 Dtor_Complete, LHS.getAddress()); 1624 } else { 1625 const RecordType *RT = 1626 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>(); 1627 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1628 if (BaseClassDecl->hasTrivialDestructor()) 1629 continue; 1630 llvm::Value *V = GetAddressCXXOfBaseClass(LoadCXXThis(), 1631 ClassDecl, BaseClassDecl, 1632 /*NullCheckValue=*/false); 1633 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()), 1634 DtorType, V); 1635 } 1636 } 1637 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial()) 1638 return; 1639 // Case of destructor synthesis with fields and base classes 1640 // which have non-trivial destructors. They must be destructed in 1641 // reverse order of their construction. 1642 llvm::SmallVector<FieldDecl *, 16> DestructedFields; 1643 1644 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1645 FieldEnd = ClassDecl->field_end(); 1646 Field != FieldEnd; ++Field) { 1647 QualType FieldType = getContext().getCanonicalType((*Field)->getType()); 1648 if (getContext().getAsConstantArrayType(FieldType)) 1649 FieldType = getContext().getBaseElementType(FieldType); 1650 if (const RecordType *RT = FieldType->getAs<RecordType>()) { 1651 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1652 if (FieldClassDecl->hasTrivialDestructor()) 1653 continue; 1654 DestructedFields.push_back(*Field); 1655 } 1656 } 1657 if (!DestructedFields.empty()) 1658 for (int i = DestructedFields.size() -1; i >= 0; --i) { 1659 FieldDecl *Field = DestructedFields[i]; 1660 QualType FieldType = Field->getType(); 1661 const ConstantArrayType *Array = 1662 getContext().getAsConstantArrayType(FieldType); 1663 if (Array) 1664 FieldType = getContext().getBaseElementType(FieldType); 1665 const RecordType *RT = FieldType->getAs<RecordType>(); 1666 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1667 llvm::Value *LoadOfThis = LoadCXXThis(); 1668 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0); 1669 if (Array) { 1670 const llvm::Type *BasePtr = ConvertType(FieldType); 1671 BasePtr = llvm::PointerType::getUnqual(BasePtr); 1672 llvm::Value *BaseAddrPtr = 1673 Builder.CreateBitCast(LHS.getAddress(), BasePtr); 1674 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()), 1675 Array, BaseAddrPtr); 1676 } 1677 else 1678 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()), 1679 Dtor_Complete, LHS.getAddress()); 1680 } 1681 1682 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases; 1683 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 1684 Base != ClassDecl->bases_end(); ++Base) { 1685 // FIXME. copy assignment of virtual base NYI 1686 if (Base->isVirtual()) 1687 continue; 1688 1689 CXXRecordDecl *BaseClassDecl 1690 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1691 if (BaseClassDecl->hasTrivialDestructor()) 1692 continue; 1693 DestructedBases.push_back(BaseClassDecl); 1694 } 1695 if (DestructedBases.empty()) 1696 return; 1697 for (int i = DestructedBases.size() -1; i >= 0; --i) { 1698 CXXRecordDecl *BaseClassDecl = DestructedBases[i]; 1699 llvm::Value *V = GetAddressCXXOfBaseClass(LoadCXXThis(), 1700 ClassDecl,BaseClassDecl, 1701 /*NullCheckValue=*/false); 1702 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()), 1703 Dtor_Complete, V); 1704 } 1705} 1706 1707void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor, 1708 CXXDtorType DtorType, 1709 llvm::Function *Fn, 1710 const FunctionArgList &Args) { 1711 1712 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1713 assert(!ClassDecl->hasUserDeclaredDestructor() && 1714 "SynthesizeDefaultDestructor - destructor has user declaration"); 1715 (void) ClassDecl; 1716 1717 StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args, 1718 SourceLocation()); 1719 EmitDtorEpilogue(Dtor, DtorType); 1720 FinishFunction(); 1721} 1722 1723// FIXME: Move this to CGCXXStmt.cpp 1724void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) { 1725 // FIXME: We need to do more here. 1726 EmitStmt(S.getTryBlock()); 1727} 1728