1 //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===// 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 to emit Objective-C code as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGDebugInfo.h" 15 #include "CGObjCRuntime.h" 16 #include "CodeGenFunction.h" 17 #include "CodeGenModule.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/StmtObjC.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/Target/TargetData.h" 24 using namespace clang; 25 using namespace CodeGen; 26 27 /// Emits an instance of NSConstantString representing the object. 28 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) 29 { 30 llvm::Constant *C = 31 CGM.getObjCRuntime().GenerateConstantString(E->getString()); 32 // FIXME: This bitcast should just be made an invariant on the Runtime. 33 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType())); 34 } 35 36 /// Emit a selector. 37 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) { 38 // Untyped selector. 39 // Note that this implementation allows for non-constant strings to be passed 40 // as arguments to @selector(). Currently, the only thing preventing this 41 // behaviour is the type checking in the front end. 42 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector()); 43 } 44 45 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) { 46 // FIXME: This should pass the Decl not the name. 47 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol()); 48 } 49 50 51 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E, 52 ReturnValueSlot Return) { 53 // Only the lookup mechanism and first two arguments of the method 54 // implementation vary between runtimes. We can get the receiver and 55 // arguments in generic code. 56 57 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 58 bool isSuperMessage = false; 59 bool isClassMessage = false; 60 ObjCInterfaceDecl *OID = 0; 61 // Find the receiver 62 llvm::Value *Receiver = 0; 63 switch (E->getReceiverKind()) { 64 case ObjCMessageExpr::Instance: 65 Receiver = EmitScalarExpr(E->getInstanceReceiver()); 66 break; 67 68 case ObjCMessageExpr::Class: { 69 const ObjCObjectType *ObjTy 70 = E->getClassReceiver()->getAs<ObjCObjectType>(); 71 assert(ObjTy && "Invalid Objective-C class message send"); 72 OID = ObjTy->getInterface(); 73 assert(OID && "Invalid Objective-C class message send"); 74 Receiver = Runtime.GetClass(Builder, OID); 75 isClassMessage = true; 76 break; 77 } 78 79 case ObjCMessageExpr::SuperInstance: 80 Receiver = LoadObjCSelf(); 81 isSuperMessage = true; 82 break; 83 84 case ObjCMessageExpr::SuperClass: 85 Receiver = LoadObjCSelf(); 86 isSuperMessage = true; 87 isClassMessage = true; 88 break; 89 } 90 91 CallArgList Args; 92 EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end()); 93 94 QualType ResultType = 95 E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType(); 96 97 if (isSuperMessage) { 98 // super is only valid in an Objective-C method 99 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 100 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext()); 101 return Runtime.GenerateMessageSendSuper(*this, Return, ResultType, 102 E->getSelector(), 103 OMD->getClassInterface(), 104 isCategoryImpl, 105 Receiver, 106 isClassMessage, 107 Args, 108 E->getMethodDecl()); 109 } 110 111 return Runtime.GenerateMessageSend(*this, Return, ResultType, 112 E->getSelector(), 113 Receiver, Args, OID, 114 E->getMethodDecl()); 115 } 116 117 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates 118 /// the LLVM function and sets the other context used by 119 /// CodeGenFunction. 120 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD, 121 const ObjCContainerDecl *CD) { 122 FunctionArgList Args; 123 // Check if we should generate debug info for this method. 124 if (CGM.getDebugInfo() && !OMD->hasAttr<NoDebugAttr>()) 125 DebugInfo = CGM.getDebugInfo(); 126 127 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD); 128 129 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD); 130 CGM.SetInternalFunctionAttributes(OMD, Fn, FI); 131 132 Args.push_back(std::make_pair(OMD->getSelfDecl(), 133 OMD->getSelfDecl()->getType())); 134 Args.push_back(std::make_pair(OMD->getCmdDecl(), 135 OMD->getCmdDecl()->getType())); 136 137 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(), 138 E = OMD->param_end(); PI != E; ++PI) 139 Args.push_back(std::make_pair(*PI, (*PI)->getType())); 140 141 CurGD = OMD; 142 143 StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocStart()); 144 } 145 146 /// Generate an Objective-C method. An Objective-C method is a C function with 147 /// its pointer, name, and types registered in the class struture. 148 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) { 149 StartObjCMethod(OMD, OMD->getClassInterface()); 150 EmitStmt(OMD->getBody()); 151 FinishFunction(OMD->getBodyRBrace()); 152 } 153 154 // FIXME: I wasn't sure about the synthesis approach. If we end up generating an 155 // AST for the whole body we can just fall back to having a GenerateFunction 156 // which takes the body Stmt. 157 158 /// GenerateObjCGetter - Generate an Objective-C property getter 159 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize 160 /// is illegal within a category. 161 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP, 162 const ObjCPropertyImplDecl *PID) { 163 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl(); 164 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 165 bool IsAtomic = 166 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic); 167 ObjCMethodDecl *OMD = PD->getGetterMethodDecl(); 168 assert(OMD && "Invalid call to generate getter (empty method)"); 169 StartObjCMethod(OMD, IMP->getClassInterface()); 170 171 // Determine if we should use an objc_getProperty call for 172 // this. Non-atomic properties are directly evaluated. 173 // atomic 'copy' and 'retain' properties are also directly 174 // evaluated in gc-only mode. 175 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly && 176 IsAtomic && 177 (PD->getSetterKind() == ObjCPropertyDecl::Copy || 178 PD->getSetterKind() == ObjCPropertyDecl::Retain)) { 179 llvm::Value *GetPropertyFn = 180 CGM.getObjCRuntime().GetPropertyGetFunction(); 181 182 if (!GetPropertyFn) { 183 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy"); 184 FinishFunction(); 185 return; 186 } 187 188 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true). 189 // FIXME: Can't this be simpler? This might even be worse than the 190 // corresponding gcc code. 191 CodeGenTypes &Types = CGM.getTypes(); 192 ValueDecl *Cmd = OMD->getCmdDecl(); 193 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd"); 194 QualType IdTy = getContext().getObjCIdType(); 195 llvm::Value *SelfAsId = 196 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 197 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar); 198 llvm::Value *True = 199 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1); 200 CallArgList Args; 201 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy)); 202 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType())); 203 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy)); 204 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy)); 205 // FIXME: We shouldn't need to get the function info here, the 206 // runtime already should have computed it to build the function. 207 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args, 208 FunctionType::ExtInfo()), 209 GetPropertyFn, ReturnValueSlot(), Args); 210 // We need to fix the type here. Ivars with copy & retain are 211 // always objects so we don't need to worry about complex or 212 // aggregates. 213 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(), 214 Types.ConvertType(PD->getType()))); 215 EmitReturnOfRValue(RV, PD->getType()); 216 } else { 217 if (Ivar->getType()->isAnyComplexType()) { 218 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 219 Ivar, 0); 220 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(), 221 LV.isVolatileQualified()); 222 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified()); 223 } 224 else if (hasAggregateLLVMType(Ivar->getType())) { 225 bool IsStrong = false; 226 if ((IsAtomic || (IsStrong = IvarTypeWithAggrGCObjects(Ivar->getType()))) 227 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect 228 && CGM.getObjCRuntime().GetGetStructFunction()) { 229 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 230 Ivar, 0); 231 llvm::Value *GetCopyStructFn = 232 CGM.getObjCRuntime().GetGetStructFunction(); 233 CodeGenTypes &Types = CGM.getTypes(); 234 // objc_copyStruct (ReturnValue, &structIvar, 235 // sizeof (Type of Ivar), isAtomic, false); 236 CallArgList Args; 237 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue, 238 Types.ConvertType(getContext().VoidPtrTy))); 239 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy)); 240 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), 241 Types.ConvertType(getContext().VoidPtrTy))); 242 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy)); 243 // sizeof (Type of Ivar) 244 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType()); 245 llvm::Value *SizeVal = 246 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy), 247 Size.getQuantity()); 248 Args.push_back(std::make_pair(RValue::get(SizeVal), 249 getContext().LongTy)); 250 llvm::Value *isAtomic = 251 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 252 IsAtomic ? 1 : 0); 253 Args.push_back(std::make_pair(RValue::get(isAtomic), 254 getContext().BoolTy)); 255 llvm::Value *hasStrong = 256 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 257 IsStrong ? 1 : 0); 258 Args.push_back(std::make_pair(RValue::get(hasStrong), 259 getContext().BoolTy)); 260 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args, 261 FunctionType::ExtInfo()), 262 GetCopyStructFn, ReturnValueSlot(), Args); 263 } 264 else { 265 if (PID->getGetterCXXConstructor()) { 266 ReturnStmt *Stmt = 267 new (getContext()) ReturnStmt(SourceLocation(), 268 PID->getGetterCXXConstructor(), 269 0); 270 EmitReturnStmt(*Stmt); 271 } 272 else { 273 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 274 Ivar, 0); 275 EmitAggregateCopy(ReturnValue, LV.getAddress(), Ivar->getType()); 276 } 277 } 278 } else { 279 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), 280 Ivar, 0); 281 CodeGenTypes &Types = CGM.getTypes(); 282 RValue RV = EmitLoadOfLValue(LV, Ivar->getType()); 283 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(), 284 Types.ConvertType(PD->getType()))); 285 EmitReturnOfRValue(RV, PD->getType()); 286 } 287 } 288 289 FinishFunction(); 290 } 291 292 /// GenerateObjCSetter - Generate an Objective-C property setter 293 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize 294 /// is illegal within a category. 295 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, 296 const ObjCPropertyImplDecl *PID) { 297 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl(); 298 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 299 ObjCMethodDecl *OMD = PD->getSetterMethodDecl(); 300 assert(OMD && "Invalid call to generate setter (empty method)"); 301 StartObjCMethod(OMD, IMP->getClassInterface()); 302 303 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy; 304 bool IsAtomic = 305 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic); 306 307 // Determine if we should use an objc_setProperty call for 308 // this. Properties with 'copy' semantics always use it, as do 309 // non-atomic properties with 'release' semantics as long as we are 310 // not in gc-only mode. 311 if (IsCopy || 312 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly && 313 PD->getSetterKind() == ObjCPropertyDecl::Retain)) { 314 llvm::Value *SetPropertyFn = 315 CGM.getObjCRuntime().GetPropertySetFunction(); 316 317 if (!SetPropertyFn) { 318 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy"); 319 FinishFunction(); 320 return; 321 } 322 323 // Emit objc_setProperty((id) self, _cmd, offset, arg, 324 // <is-atomic>, <is-copy>). 325 // FIXME: Can't this be simpler? This might even be worse than the 326 // corresponding gcc code. 327 CodeGenTypes &Types = CGM.getTypes(); 328 ValueDecl *Cmd = OMD->getCmdDecl(); 329 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd"); 330 QualType IdTy = getContext().getObjCIdType(); 331 llvm::Value *SelfAsId = 332 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 333 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar); 334 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()]; 335 llvm::Value *ArgAsId = 336 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"), 337 Types.ConvertType(IdTy)); 338 llvm::Value *True = 339 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1); 340 llvm::Value *False = 341 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0); 342 CallArgList Args; 343 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy)); 344 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType())); 345 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy)); 346 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy)); 347 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False), 348 getContext().BoolTy)); 349 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False), 350 getContext().BoolTy)); 351 // FIXME: We shouldn't need to get the function info here, the runtime 352 // already should have computed it to build the function. 353 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args, 354 FunctionType::ExtInfo()), 355 SetPropertyFn, 356 ReturnValueSlot(), Args); 357 } else if (IsAtomic && hasAggregateLLVMType(Ivar->getType()) && 358 !Ivar->getType()->isAnyComplexType() && 359 IndirectObjCSetterArg(*CurFnInfo) 360 && CGM.getObjCRuntime().GetSetStructFunction()) { 361 // objc_copyStruct (&structIvar, &Arg, 362 // sizeof (struct something), true, false); 363 llvm::Value *GetCopyStructFn = 364 CGM.getObjCRuntime().GetSetStructFunction(); 365 CodeGenTypes &Types = CGM.getTypes(); 366 CallArgList Args; 367 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0); 368 RValue RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), 369 Types.ConvertType(getContext().VoidPtrTy))); 370 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy)); 371 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()]; 372 llvm::Value *ArgAsPtrTy = 373 Builder.CreateBitCast(Arg, 374 Types.ConvertType(getContext().VoidPtrTy)); 375 RV = RValue::get(ArgAsPtrTy); 376 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy)); 377 // sizeof (Type of Ivar) 378 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType()); 379 llvm::Value *SizeVal = 380 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy), 381 Size.getQuantity()); 382 Args.push_back(std::make_pair(RValue::get(SizeVal), 383 getContext().LongTy)); 384 llvm::Value *True = 385 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1); 386 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy)); 387 llvm::Value *False = 388 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0); 389 Args.push_back(std::make_pair(RValue::get(False), getContext().BoolTy)); 390 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args, 391 FunctionType::ExtInfo()), 392 GetCopyStructFn, ReturnValueSlot(), Args); 393 } else if (PID->getSetterCXXAssignment()) { 394 EmitIgnoredExpr(PID->getSetterCXXAssignment()); 395 } else { 396 // FIXME: Find a clean way to avoid AST node creation. 397 SourceLocation Loc = PD->getLocation(); 398 ValueDecl *Self = OMD->getSelfDecl(); 399 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl(); 400 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc); 401 ParmVarDecl *ArgDecl = *OMD->param_begin(); 402 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), VK_LValue, Loc); 403 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true); 404 405 // The property type can differ from the ivar type in some situations with 406 // Objective-C pointer types, we can always bit cast the RHS in these cases. 407 if (getContext().getCanonicalType(Ivar->getType()) != 408 getContext().getCanonicalType(ArgDecl->getType())) { 409 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack, 410 Ivar->getType(), CK_BitCast, &Arg, 411 VK_RValue); 412 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign, 413 Ivar->getType(), VK_RValue, OK_Ordinary, Loc); 414 EmitStmt(&Assign); 415 } else { 416 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign, 417 Ivar->getType(), VK_RValue, OK_Ordinary, Loc); 418 EmitStmt(&Assign); 419 } 420 } 421 422 FinishFunction(); 423 } 424 425 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 426 ObjCMethodDecl *MD, 427 bool ctor) { 428 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers; 429 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface()); 430 StartObjCMethod(MD, IMP->getClassInterface()); 431 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(), 432 E = IMP->init_end(); B != E; ++B) { 433 CXXCtorInitializer *Member = (*B); 434 IvarInitializers.push_back(Member); 435 } 436 if (ctor) { 437 for (unsigned I = 0, E = IvarInitializers.size(); I != E; ++I) { 438 CXXCtorInitializer *IvarInit = IvarInitializers[I]; 439 FieldDecl *Field = IvarInit->getAnyMember(); 440 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); 441 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), 442 LoadObjCSelf(), Ivar, 0); 443 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true)); 444 } 445 // constructor returns 'self'. 446 CodeGenTypes &Types = CGM.getTypes(); 447 QualType IdTy(CGM.getContext().getObjCIdType()); 448 llvm::Value *SelfAsId = 449 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 450 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy); 451 } else { 452 // dtor 453 for (size_t i = IvarInitializers.size(); i > 0; --i) { 454 FieldDecl *Field = IvarInitializers[i - 1]->getAnyMember(); 455 QualType FieldType = Field->getType(); 456 const ConstantArrayType *Array = 457 getContext().getAsConstantArrayType(FieldType); 458 if (Array) 459 FieldType = getContext().getBaseElementType(FieldType); 460 461 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); 462 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), 463 LoadObjCSelf(), Ivar, 0); 464 const RecordType *RT = FieldType->getAs<RecordType>(); 465 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 466 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(); 467 if (!Dtor->isTrivial()) { 468 if (Array) { 469 const llvm::Type *BasePtr = ConvertType(FieldType); 470 BasePtr = llvm::PointerType::getUnqual(BasePtr); 471 llvm::Value *BaseAddrPtr = 472 Builder.CreateBitCast(LV.getAddress(), BasePtr); 473 EmitCXXAggrDestructorCall(Dtor, 474 Array, BaseAddrPtr); 475 } else { 476 EmitCXXDestructorCall(Dtor, 477 Dtor_Complete, /*ForVirtualBase=*/false, 478 LV.getAddress()); 479 } 480 } 481 } 482 } 483 FinishFunction(); 484 } 485 486 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) { 487 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(); 488 it++; it++; 489 const ABIArgInfo &AI = it->info; 490 // FIXME. Is this sufficient check? 491 return (AI.getKind() == ABIArgInfo::Indirect); 492 } 493 494 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) { 495 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) 496 return false; 497 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>()) 498 return FDTTy->getDecl()->hasObjectMember(); 499 return false; 500 } 501 502 llvm::Value *CodeGenFunction::LoadObjCSelf() { 503 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 504 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self"); 505 } 506 507 QualType CodeGenFunction::TypeOfSelfObject() { 508 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 509 ImplicitParamDecl *selfDecl = OMD->getSelfDecl(); 510 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>( 511 getContext().getCanonicalType(selfDecl->getType())); 512 return PTy->getPointeeType(); 513 } 514 515 LValue 516 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) { 517 // This is a special l-value that just issues sends when we load or 518 // store through it. 519 520 // For certain base kinds, we need to emit the base immediately. 521 llvm::Value *Base; 522 if (E->isSuperReceiver()) 523 Base = LoadObjCSelf(); 524 else if (E->isClassReceiver()) 525 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver()); 526 else 527 Base = EmitScalarExpr(E->getBase()); 528 return LValue::MakePropertyRef(E, Base); 529 } 530 531 static RValue GenerateMessageSendSuper(CodeGenFunction &CGF, 532 ReturnValueSlot Return, 533 QualType ResultType, 534 Selector S, 535 llvm::Value *Receiver, 536 const CallArgList &CallArgs) { 537 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl); 538 bool isClassMessage = OMD->isClassMethod(); 539 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext()); 540 return CGF.CGM.getObjCRuntime() 541 .GenerateMessageSendSuper(CGF, Return, ResultType, 542 S, OMD->getClassInterface(), 543 isCategoryImpl, Receiver, 544 isClassMessage, CallArgs); 545 } 546 547 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV, 548 ReturnValueSlot Return) { 549 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr(); 550 QualType ResultType; 551 Selector S; 552 if (E->isExplicitProperty()) { 553 const ObjCPropertyDecl *Property = E->getExplicitProperty(); 554 S = Property->getGetterName(); 555 ResultType = E->getType(); 556 } else { 557 const ObjCMethodDecl *Getter = E->getImplicitPropertyGetter(); 558 S = Getter->getSelector(); 559 ResultType = Getter->getResultType(); // with reference! 560 } 561 562 llvm::Value *Receiver = LV.getPropertyRefBaseAddr(); 563 564 // Accesses to 'super' follow a different code path. 565 if (E->isSuperReceiver()) 566 return GenerateMessageSendSuper(*this, Return, ResultType, 567 S, Receiver, CallArgList()); 568 569 const ObjCInterfaceDecl *ReceiverClass 570 = (E->isClassReceiver() ? E->getClassReceiver() : 0); 571 return CGM.getObjCRuntime(). 572 GenerateMessageSend(*this, Return, ResultType, S, 573 Receiver, CallArgList(), ReceiverClass); 574 } 575 576 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src, 577 LValue Dst) { 578 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr(); 579 Selector S = E->getSetterSelector(); 580 QualType ArgType; 581 if (E->isImplicitProperty()) { 582 const ObjCMethodDecl *Setter = E->getImplicitPropertySetter(); 583 ObjCMethodDecl::param_iterator P = Setter->param_begin(); 584 ArgType = (*P)->getType(); 585 } else { 586 ArgType = E->getType(); 587 } 588 589 CallArgList Args; 590 Args.push_back(std::make_pair(Src, ArgType)); 591 592 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr(); 593 QualType ResultType = getContext().VoidTy; 594 595 if (E->isSuperReceiver()) { 596 GenerateMessageSendSuper(*this, ReturnValueSlot(), 597 ResultType, S, Receiver, Args); 598 return; 599 } 600 601 const ObjCInterfaceDecl *ReceiverClass 602 = (E->isClassReceiver() ? E->getClassReceiver() : 0); 603 604 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 605 ResultType, S, Receiver, Args, 606 ReceiverClass); 607 } 608 609 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ 610 llvm::Constant *EnumerationMutationFn = 611 CGM.getObjCRuntime().EnumerationMutationFunction(); 612 613 if (!EnumerationMutationFn) { 614 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime"); 615 return; 616 } 617 618 CGDebugInfo *DI = getDebugInfo(); 619 if (DI) { 620 DI->setLocation(S.getSourceRange().getBegin()); 621 DI->EmitRegionStart(Builder); 622 } 623 624 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end"); 625 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next"); 626 627 // Fast enumeration state. 628 QualType StateTy = getContext().getObjCFastEnumerationStateType(); 629 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr"); 630 EmitNullInitialization(StatePtr, StateTy); 631 632 // Number of elements in the items array. 633 static const unsigned NumItems = 16; 634 635 // Fetch the countByEnumeratingWithState:objects:count: selector. 636 IdentifierInfo *II[] = { 637 &CGM.getContext().Idents.get("countByEnumeratingWithState"), 638 &CGM.getContext().Idents.get("objects"), 639 &CGM.getContext().Idents.get("count") 640 }; 641 Selector FastEnumSel = 642 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]); 643 644 QualType ItemsTy = 645 getContext().getConstantArrayType(getContext().getObjCIdType(), 646 llvm::APInt(32, NumItems), 647 ArrayType::Normal, 0); 648 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr"); 649 650 // Emit the collection pointer. 651 llvm::Value *Collection = EmitScalarExpr(S.getCollection()); 652 653 // Send it our message: 654 CallArgList Args; 655 656 // The first argument is a temporary of the enumeration-state type. 657 Args.push_back(std::make_pair(RValue::get(StatePtr), 658 getContext().getPointerType(StateTy))); 659 660 // The second argument is a temporary array with space for NumItems 661 // pointers. We'll actually be loading elements from the array 662 // pointer written into the control state; this buffer is so that 663 // collections that *aren't* backed by arrays can still queue up 664 // batches of elements. 665 Args.push_back(std::make_pair(RValue::get(ItemsPtr), 666 getContext().getPointerType(ItemsTy))); 667 668 // The third argument is the capacity of that temporary array. 669 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy); 670 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems); 671 Args.push_back(std::make_pair(RValue::get(Count), 672 getContext().UnsignedLongTy)); 673 674 // Start the enumeration. 675 RValue CountRV = 676 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 677 getContext().UnsignedLongTy, 678 FastEnumSel, 679 Collection, Args); 680 681 // The initial number of objects that were returned in the buffer. 682 llvm::Value *initialBufferLimit = CountRV.getScalarVal(); 683 684 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty"); 685 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit"); 686 687 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy); 688 689 // If the limit pointer was zero to begin with, the collection is 690 // empty; skip all this. 691 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), 692 EmptyBB, LoopInitBB); 693 694 // Otherwise, initialize the loop. 695 EmitBlock(LoopInitBB); 696 697 // Save the initial mutations value. This is the value at an 698 // address that was written into the state object by 699 // countByEnumeratingWithState:objects:count:. 700 llvm::Value *StateMutationsPtrPtr = 701 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr"); 702 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, 703 "mutationsptr"); 704 705 llvm::Value *initialMutations = 706 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations"); 707 708 // Start looping. This is the point we return to whenever we have a 709 // fresh, non-empty batch of objects. 710 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody"); 711 EmitBlock(LoopBodyBB); 712 713 // The current index into the buffer. 714 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, "forcoll.index"); 715 index->addIncoming(zero, LoopInitBB); 716 717 // The current buffer size. 718 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, "forcoll.count"); 719 count->addIncoming(initialBufferLimit, LoopInitBB); 720 721 // Check whether the mutations value has changed from where it was 722 // at start. StateMutationsPtr should actually be invariant between 723 // refreshes. 724 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr"); 725 llvm::Value *currentMutations 726 = Builder.CreateLoad(StateMutationsPtr, "statemutations"); 727 728 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated"); 729 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcool.notmutated"); 730 731 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations), 732 WasNotMutatedBB, WasMutatedBB); 733 734 // If so, call the enumeration-mutation function. 735 EmitBlock(WasMutatedBB); 736 llvm::Value *V = 737 Builder.CreateBitCast(Collection, 738 ConvertType(getContext().getObjCIdType()), 739 "tmp"); 740 CallArgList Args2; 741 Args2.push_back(std::make_pair(RValue::get(V), 742 getContext().getObjCIdType())); 743 // FIXME: We shouldn't need to get the function info here, the runtime already 744 // should have computed it to build the function. 745 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2, 746 FunctionType::ExtInfo()), 747 EnumerationMutationFn, ReturnValueSlot(), Args2); 748 749 // Otherwise, or if the mutation function returns, just continue. 750 EmitBlock(WasNotMutatedBB); 751 752 // Initialize the element variable. 753 RunCleanupsScope elementVariableScope(*this); 754 bool elementIsDecl; 755 LValue elementLValue; 756 QualType elementType; 757 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) { 758 EmitStmt(SD); 759 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl()); 760 761 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(), 762 VK_LValue, SourceLocation()); 763 elementLValue = EmitLValue(&tempDRE); 764 elementType = D->getType(); 765 elementIsDecl = true; 766 } else { 767 elementLValue = LValue(); // suppress warning 768 elementType = cast<Expr>(S.getElement())->getType(); 769 elementIsDecl = false; 770 } 771 const llvm::Type *convertedElementType = ConvertType(elementType); 772 773 // Fetch the buffer out of the enumeration state. 774 // TODO: this pointer should actually be invariant between 775 // refreshes, which would help us do certain loop optimizations. 776 llvm::Value *StateItemsPtr = 777 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr"); 778 llvm::Value *EnumStateItems = 779 Builder.CreateLoad(StateItemsPtr, "stateitems"); 780 781 // Fetch the value at the current index from the buffer. 782 llvm::Value *CurrentItemPtr = 783 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr"); 784 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr); 785 786 // Cast that value to the right type. 787 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType, 788 "currentitem"); 789 790 // Make sure we have an l-value. Yes, this gets evaluated every 791 // time through the loop. 792 if (!elementIsDecl) 793 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 794 795 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType); 796 797 // Perform the loop body, setting up break and continue labels. 798 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody)); 799 { 800 RunCleanupsScope Scope(*this); 801 EmitStmt(S.getBody()); 802 } 803 BreakContinueStack.pop_back(); 804 805 // Destroy the element variable now. 806 elementVariableScope.ForceCleanup(); 807 808 // Check whether there are more elements. 809 EmitBlock(AfterBody.getBlock()); 810 811 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch"); 812 813 // First we check in the local buffer. 814 llvm::Value *indexPlusOne 815 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1)); 816 817 // If we haven't overrun the buffer yet, we can continue. 818 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count), 819 LoopBodyBB, FetchMoreBB); 820 821 index->addIncoming(indexPlusOne, AfterBody.getBlock()); 822 count->addIncoming(count, AfterBody.getBlock()); 823 824 // Otherwise, we have to fetch more elements. 825 EmitBlock(FetchMoreBB); 826 827 CountRV = 828 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 829 getContext().UnsignedLongTy, 830 FastEnumSel, 831 Collection, Args); 832 833 // If we got a zero count, we're done. 834 llvm::Value *refetchCount = CountRV.getScalarVal(); 835 836 // (note that the message send might split FetchMoreBB) 837 index->addIncoming(zero, Builder.GetInsertBlock()); 838 count->addIncoming(refetchCount, Builder.GetInsertBlock()); 839 840 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero), 841 EmptyBB, LoopBodyBB); 842 843 // No more elements. 844 EmitBlock(EmptyBB); 845 846 if (!elementIsDecl) { 847 // If the element was not a declaration, set it to be null. 848 849 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType); 850 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 851 EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType); 852 } 853 854 if (DI) { 855 DI->setLocation(S.getSourceRange().getEnd()); 856 DI->EmitRegionEnd(Builder); 857 } 858 859 EmitBlock(LoopEnd.getBlock()); 860 } 861 862 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) { 863 CGM.getObjCRuntime().EmitTryStmt(*this, S); 864 } 865 866 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) { 867 CGM.getObjCRuntime().EmitThrowStmt(*this, S); 868 } 869 870 void CodeGenFunction::EmitObjCAtSynchronizedStmt( 871 const ObjCAtSynchronizedStmt &S) { 872 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S); 873 } 874 875 CGObjCRuntime::~CGObjCRuntime() {} 876