CGCXX.cpp revision 17945a0f64fe03ff6ec0c2146005a87636e3ac12
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/Decl.h" 21#include "clang/AST/DeclCXX.h" 22#include "clang/AST/DeclObjC.h" 23#include "llvm/ADT/StringExtras.h" 24using namespace clang; 25using namespace CodeGen; 26 27void 28CodeGenFunction::GenerateStaticCXXBlockVarDeclInit(const VarDecl &D, 29 llvm::GlobalVariable *GV) { 30 // FIXME: This should use __cxa_guard_{acquire,release}? 31 32 assert(!getContext().getLangOptions().ThreadsafeStatics && 33 "thread safe statics are currently not supported!"); 34 35 llvm::SmallString<256> GuardVName; 36 llvm::raw_svector_ostream GuardVOut(GuardVName); 37 mangleGuardVariable(&D, getContext(), GuardVOut); 38 39 // Create the guard variable. 40 llvm::GlobalValue *GuardV = 41 new llvm::GlobalVariable(llvm::Type::Int64Ty, false, 42 GV->getLinkage(), 43 llvm::Constant::getNullValue(llvm::Type::Int64Ty), 44 GuardVName.c_str(), 45 &CGM.getModule()); 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 const llvm::Type *Ty = 110 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 111 FPT->isVariadic()); 112 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty); 113 114 llvm::Value *This; 115 116 if (ME->isArrow()) 117 This = EmitScalarExpr(ME->getBase()); 118 else { 119 LValue BaseLV = EmitLValue(ME->getBase()); 120 This = BaseLV.getAddress(); 121 } 122 123 return EmitCXXMemberCall(MD, Callee, This, 124 CE->arg_begin(), CE->arg_end()); 125} 126 127RValue 128CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 129 const CXXMethodDecl *MD) { 130 assert(MD->isInstance() && 131 "Trying to emit a member call expr on a static method!"); 132 133 134 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType(); 135 const llvm::Type *Ty = 136 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 137 FPT->isVariadic()); 138 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty); 139 140 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress(); 141 142 return EmitCXXMemberCall(MD, Callee, This, 143 E->arg_begin() + 1, E->arg_end()); 144} 145 146llvm::Value *CodeGenFunction::LoadCXXThis() { 147 assert(isa<CXXMethodDecl>(CurFuncDecl) && 148 "Must be in a C++ member function decl to load 'this'"); 149 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() && 150 "Must be in a C++ member function decl to load 'this'"); 151 152 // FIXME: What if we're inside a block? 153 // ans: See how CodeGenFunction::LoadObjCSelf() uses 154 // CodeGenFunction::BlockForwardSelf() for how to do this. 155 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this"); 156} 157 158void 159CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 160 CXXCtorType Type, 161 llvm::Value *This, 162 CallExpr::const_arg_iterator ArgBeg, 163 CallExpr::const_arg_iterator ArgEnd) { 164 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); 165 166 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd); 167} 168 169void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D, 170 CXXDtorType Type, 171 llvm::Value *This) { 172 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type); 173 174 EmitCXXMemberCall(D, Callee, This, 0, 0); 175} 176 177void 178CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest, 179 const CXXConstructExpr *E) { 180 assert(Dest && "Must have a destination!"); 181 182 const CXXRecordDecl *RD = 183 cast<CXXRecordDecl>(E->getType()->getAsRecordType()->getDecl()); 184 if (RD->hasTrivialConstructor()) 185 return; 186 187 // Call the constructor. 188 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest, 189 E->arg_begin(), E->arg_end()); 190} 191 192llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 193 if (E->isArray()) { 194 ErrorUnsupported(E, "new[] expression"); 195 return llvm::UndefValue::get(ConvertType(E->getType())); 196 } 197 198 QualType AllocType = E->getAllocatedType(); 199 FunctionDecl *NewFD = E->getOperatorNew(); 200 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType(); 201 202 CallArgList NewArgs; 203 204 // The allocation size is the first argument. 205 QualType SizeTy = getContext().getSizeType(); 206 llvm::Value *AllocSize = 207 llvm::ConstantInt::get(ConvertType(SizeTy), 208 getContext().getTypeSize(AllocType) / 8); 209 210 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy)); 211 212 // Emit the rest of the arguments. 213 // FIXME: Ideally, this should just use EmitCallArgs. 214 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin(); 215 216 // First, use the types from the function type. 217 // We start at 1 here because the first argument (the allocation size) 218 // has already been emitted. 219 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) { 220 QualType ArgType = NewFTy->getArgType(i); 221 222 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 223 getTypePtr() == 224 getContext().getCanonicalType(NewArg->getType()).getTypePtr() && 225 "type mismatch in call argument!"); 226 227 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType), 228 ArgType)); 229 230 } 231 232 // Either we've emitted all the call args, or we have a call to a 233 // variadic function. 234 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) && 235 "Extra arguments in non-variadic function!"); 236 237 // If we still have any arguments, emit them using the type of the argument. 238 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end(); 239 NewArg != NewArgEnd; ++NewArg) { 240 QualType ArgType = NewArg->getType(); 241 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType), 242 ArgType)); 243 } 244 245 // Emit the call to new. 246 RValue RV = 247 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs), 248 CGM.GetAddrOfFunction(GlobalDecl(NewFD)), 249 NewArgs, NewFD); 250 251 // If an allocation function is declared with an empty exception specification 252 // it returns null to indicate failure to allocate storage. [expr.new]p13. 253 // (We don't need to check for null when there's no new initializer and 254 // we're allocating a POD type). 255 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() && 256 !(AllocType->isPODType() && !E->hasInitializer()); 257 258 llvm::BasicBlock *NewNull = 0; 259 llvm::BasicBlock *NewNotNull = 0; 260 llvm::BasicBlock *NewEnd = 0; 261 262 llvm::Value *NewPtr = RV.getScalarVal(); 263 264 if (NullCheckResult) { 265 NewNull = createBasicBlock("new.null"); 266 NewNotNull = createBasicBlock("new.notnull"); 267 NewEnd = createBasicBlock("new.end"); 268 269 llvm::Value *IsNull = 270 Builder.CreateICmpEQ(NewPtr, 271 llvm::Constant::getNullValue(NewPtr->getType()), 272 "isnull"); 273 274 Builder.CreateCondBr(IsNull, NewNull, NewNotNull); 275 EmitBlock(NewNotNull); 276 } 277 278 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType())); 279 280 if (AllocType->isPODType()) { 281 if (E->getNumConstructorArgs() > 0) { 282 assert(E->getNumConstructorArgs() == 1 && 283 "Can only have one argument to initializer of POD type."); 284 285 const Expr *Init = E->getConstructorArg(0); 286 287 if (!hasAggregateLLVMType(AllocType)) 288 Builder.CreateStore(EmitScalarExpr(Init), NewPtr); 289 else if (AllocType->isAnyComplexType()) 290 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified()); 291 else 292 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified()); 293 } 294 } else { 295 // Call the constructor. 296 CXXConstructorDecl *Ctor = E->getConstructor(); 297 298 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr, 299 E->constructor_arg_begin(), 300 E->constructor_arg_end()); 301 } 302 303 if (NullCheckResult) { 304 Builder.CreateBr(NewEnd); 305 EmitBlock(NewNull); 306 Builder.CreateBr(NewEnd); 307 EmitBlock(NewEnd); 308 309 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType()); 310 PHI->reserveOperandSpace(2); 311 PHI->addIncoming(NewPtr, NewNotNull); 312 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull); 313 314 NewPtr = PHI; 315 } 316 317 return NewPtr; 318} 319 320static bool canGenerateCXXstructor(const CXXRecordDecl *RD, 321 ASTContext &Context) { 322 // The class has base classes - we don't support that right now. 323 if (RD->getNumBases() > 0) 324 return false; 325 326 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 327 I != E; ++I) { 328 // We don't support ctors for fields that aren't POD. 329 if (!I->getType()->isPODType()) 330 return false; 331 } 332 333 return true; 334} 335 336void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) { 337 if (!canGenerateCXXstructor(D->getParent(), getContext())) { 338 ErrorUnsupported(D, "C++ constructor", true); 339 return; 340 } 341 342 EmitGlobal(GlobalDecl(D, Ctor_Complete)); 343 EmitGlobal(GlobalDecl(D, Ctor_Base)); 344} 345 346void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D, 347 CXXCtorType Type) { 348 349 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type); 350 351 CodeGenFunction(*this).GenerateCode(D, Fn); 352 353 SetFunctionDefinitionAttributes(D, Fn); 354 SetLLVMFunctionAttributesForDefinition(D, Fn); 355} 356 357llvm::Function * 358CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D, 359 CXXCtorType Type) { 360 const llvm::FunctionType *FTy = 361 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false); 362 363 const char *Name = getMangledCXXCtorName(D, Type); 364 return cast<llvm::Function>( 365 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); 366} 367 368const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D, 369 CXXCtorType Type) { 370 llvm::SmallString<256> Name; 371 llvm::raw_svector_ostream Out(Name); 372 mangleCXXCtor(D, Type, Context, Out); 373 374 Name += '\0'; 375 return UniqueMangledName(Name.begin(), Name.end()); 376} 377 378void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) { 379 if (!canGenerateCXXstructor(D->getParent(), getContext())) { 380 ErrorUnsupported(D, "C++ destructor", true); 381 return; 382 } 383 384 EmitCXXDestructor(D, Dtor_Complete); 385 EmitCXXDestructor(D, Dtor_Base); 386} 387 388void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D, 389 CXXDtorType Type) { 390 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type); 391 392 CodeGenFunction(*this).GenerateCode(D, Fn); 393 394 SetFunctionDefinitionAttributes(D, Fn); 395 SetLLVMFunctionAttributesForDefinition(D, Fn); 396} 397 398llvm::Function * 399CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D, 400 CXXDtorType Type) { 401 const llvm::FunctionType *FTy = 402 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false); 403 404 const char *Name = getMangledCXXDtorName(D, Type); 405 return cast<llvm::Function>( 406 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); 407} 408 409const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D, 410 CXXDtorType Type) { 411 llvm::SmallString<256> Name; 412 llvm::raw_svector_ostream Out(Name); 413 mangleCXXDtor(D, Type, Context, Out); 414 415 Name += '\0'; 416 return UniqueMangledName(Name.begin(), Name.end()); 417} 418