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 "TargetInfo.h" 19 #include "clang/AST/ASTContext.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/StmtObjC.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/Target/TargetData.h" 25 #include "llvm/InlineAsm.h" 26 using namespace clang; 27 using namespace CodeGen; 28 29 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult; 30 static TryEmitResult 31 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e); 32 static RValue AdjustRelatedResultType(CodeGenFunction &CGF, 33 const Expr *E, 34 const ObjCMethodDecl *Method, 35 RValue Result); 36 37 /// Given the address of a variable of pointer type, find the correct 38 /// null to store into it. 39 static llvm::Constant *getNullForVariable(llvm::Value *addr) { 40 llvm::Type *type = 41 cast<llvm::PointerType>(addr->getType())->getElementType(); 42 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type)); 43 } 44 45 /// Emits an instance of NSConstantString representing the object. 46 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) 47 { 48 llvm::Constant *C = 49 CGM.getObjCRuntime().GenerateConstantString(E->getString()); 50 // FIXME: This bitcast should just be made an invariant on the Runtime. 51 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType())); 52 } 53 54 /// EmitObjCNumericLiteral - This routine generates code for 55 /// the appropriate +[NSNumber numberWith<Type>:] method. 56 /// 57 llvm::Value *CodeGenFunction::EmitObjCNumericLiteral(const ObjCNumericLiteral *E) { 58 // Generate the correct selector for this literal's concrete type. 59 const Expr *NL = E->getNumber(); 60 // Get the method. 61 const ObjCMethodDecl *Method = E->getObjCNumericLiteralMethod(); 62 assert(Method && "NSNumber method is null"); 63 Selector Sel = Method->getSelector(); 64 65 // Generate a reference to the class pointer, which will be the receiver. 66 QualType ResultType = E->getType(); // should be NSNumber * 67 const ObjCObjectPointerType *InterfacePointerType = 68 ResultType->getAsObjCInterfacePointerType(); 69 ObjCInterfaceDecl *NSNumberDecl = 70 InterfacePointerType->getObjectType()->getInterface(); 71 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 72 llvm::Value *Receiver = Runtime.GetClass(Builder, NSNumberDecl); 73 74 const ParmVarDecl *argDecl = *Method->param_begin(); 75 QualType ArgQT = argDecl->getType().getUnqualifiedType(); 76 RValue RV = EmitAnyExpr(NL); 77 CallArgList Args; 78 Args.add(RV, ArgQT); 79 80 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 81 ResultType, Sel, Receiver, Args, 82 NSNumberDecl, Method); 83 return Builder.CreateBitCast(result.getScalarVal(), 84 ConvertType(E->getType())); 85 } 86 87 llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E, 88 const ObjCMethodDecl *MethodWithObjects) { 89 ASTContext &Context = CGM.getContext(); 90 const ObjCDictionaryLiteral *DLE = 0; 91 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E); 92 if (!ALE) 93 DLE = cast<ObjCDictionaryLiteral>(E); 94 95 // Compute the type of the array we're initializing. 96 uint64_t NumElements = 97 ALE ? ALE->getNumElements() : DLE->getNumElements(); 98 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()), 99 NumElements); 100 QualType ElementType = Context.getObjCIdType().withConst(); 101 QualType ElementArrayType 102 = Context.getConstantArrayType(ElementType, APNumElements, 103 ArrayType::Normal, /*IndexTypeQuals=*/0); 104 105 // Allocate the temporary array(s). 106 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects"); 107 llvm::Value *Keys = 0; 108 if (DLE) 109 Keys = CreateMemTemp(ElementArrayType, "keys"); 110 111 // Perform the actual initialialization of the array(s). 112 for (uint64_t i = 0; i < NumElements; i++) { 113 if (ALE) { 114 // Emit the initializer. 115 const Expr *Rhs = ALE->getElement(i); 116 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i), 117 ElementType, 118 Context.getTypeAlignInChars(Rhs->getType()), 119 Context); 120 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false); 121 } else { 122 // Emit the key initializer. 123 const Expr *Key = DLE->getKeyValueElement(i).Key; 124 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i), 125 ElementType, 126 Context.getTypeAlignInChars(Key->getType()), 127 Context); 128 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false); 129 130 // Emit the value initializer. 131 const Expr *Value = DLE->getKeyValueElement(i).Value; 132 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i), 133 ElementType, 134 Context.getTypeAlignInChars(Value->getType()), 135 Context); 136 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false); 137 } 138 } 139 140 // Generate the argument list. 141 CallArgList Args; 142 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin(); 143 const ParmVarDecl *argDecl = *PI++; 144 QualType ArgQT = argDecl->getType().getUnqualifiedType(); 145 Args.add(RValue::get(Objects), ArgQT); 146 if (DLE) { 147 argDecl = *PI++; 148 ArgQT = argDecl->getType().getUnqualifiedType(); 149 Args.add(RValue::get(Keys), ArgQT); 150 } 151 argDecl = *PI; 152 ArgQT = argDecl->getType().getUnqualifiedType(); 153 llvm::Value *Count = 154 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements); 155 Args.add(RValue::get(Count), ArgQT); 156 157 // Generate a reference to the class pointer, which will be the receiver. 158 Selector Sel = MethodWithObjects->getSelector(); 159 QualType ResultType = E->getType(); 160 const ObjCObjectPointerType *InterfacePointerType 161 = ResultType->getAsObjCInterfacePointerType(); 162 ObjCInterfaceDecl *Class 163 = InterfacePointerType->getObjectType()->getInterface(); 164 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 165 llvm::Value *Receiver = Runtime.GetClass(Builder, Class); 166 167 // Generate the message send. 168 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 169 MethodWithObjects->getResultType(), 170 Sel, 171 Receiver, Args, Class, 172 MethodWithObjects); 173 return Builder.CreateBitCast(result.getScalarVal(), 174 ConvertType(E->getType())); 175 } 176 177 llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) { 178 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod()); 179 } 180 181 llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral( 182 const ObjCDictionaryLiteral *E) { 183 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod()); 184 } 185 186 /// Emit a selector. 187 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) { 188 // Untyped selector. 189 // Note that this implementation allows for non-constant strings to be passed 190 // as arguments to @selector(). Currently, the only thing preventing this 191 // behaviour is the type checking in the front end. 192 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector()); 193 } 194 195 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) { 196 // FIXME: This should pass the Decl not the name. 197 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol()); 198 } 199 200 /// \brief Adjust the type of the result of an Objective-C message send 201 /// expression when the method has a related result type. 202 static RValue AdjustRelatedResultType(CodeGenFunction &CGF, 203 const Expr *E, 204 const ObjCMethodDecl *Method, 205 RValue Result) { 206 if (!Method) 207 return Result; 208 209 if (!Method->hasRelatedResultType() || 210 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) || 211 !Result.isScalar()) 212 return Result; 213 214 // We have applied a related result type. Cast the rvalue appropriately. 215 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(), 216 CGF.ConvertType(E->getType()))); 217 } 218 219 /// Decide whether to extend the lifetime of the receiver of a 220 /// returns-inner-pointer message. 221 static bool 222 shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) { 223 switch (message->getReceiverKind()) { 224 225 // For a normal instance message, we should extend unless the 226 // receiver is loaded from a variable with precise lifetime. 227 case ObjCMessageExpr::Instance: { 228 const Expr *receiver = message->getInstanceReceiver(); 229 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver); 230 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true; 231 receiver = ice->getSubExpr()->IgnoreParens(); 232 233 // Only __strong variables. 234 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 235 return true; 236 237 // All ivars and fields have precise lifetime. 238 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver)) 239 return false; 240 241 // Otherwise, check for variables. 242 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr()); 243 if (!declRef) return true; 244 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl()); 245 if (!var) return true; 246 247 // All variables have precise lifetime except local variables with 248 // automatic storage duration that aren't specially marked. 249 return (var->hasLocalStorage() && 250 !var->hasAttr<ObjCPreciseLifetimeAttr>()); 251 } 252 253 case ObjCMessageExpr::Class: 254 case ObjCMessageExpr::SuperClass: 255 // It's never necessary for class objects. 256 return false; 257 258 case ObjCMessageExpr::SuperInstance: 259 // We generally assume that 'self' lives throughout a method call. 260 return false; 261 } 262 263 llvm_unreachable("invalid receiver kind"); 264 } 265 266 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E, 267 ReturnValueSlot Return) { 268 // Only the lookup mechanism and first two arguments of the method 269 // implementation vary between runtimes. We can get the receiver and 270 // arguments in generic code. 271 272 bool isDelegateInit = E->isDelegateInitCall(); 273 274 const ObjCMethodDecl *method = E->getMethodDecl(); 275 276 // We don't retain the receiver in delegate init calls, and this is 277 // safe because the receiver value is always loaded from 'self', 278 // which we zero out. We don't want to Block_copy block receivers, 279 // though. 280 bool retainSelf = 281 (!isDelegateInit && 282 CGM.getLangOpts().ObjCAutoRefCount && 283 method && 284 method->hasAttr<NSConsumesSelfAttr>()); 285 286 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 287 bool isSuperMessage = false; 288 bool isClassMessage = false; 289 ObjCInterfaceDecl *OID = 0; 290 // Find the receiver 291 QualType ReceiverType; 292 llvm::Value *Receiver = 0; 293 switch (E->getReceiverKind()) { 294 case ObjCMessageExpr::Instance: 295 ReceiverType = E->getInstanceReceiver()->getType(); 296 if (retainSelf) { 297 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this, 298 E->getInstanceReceiver()); 299 Receiver = ter.getPointer(); 300 if (ter.getInt()) retainSelf = false; 301 } else 302 Receiver = EmitScalarExpr(E->getInstanceReceiver()); 303 break; 304 305 case ObjCMessageExpr::Class: { 306 ReceiverType = E->getClassReceiver(); 307 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>(); 308 assert(ObjTy && "Invalid Objective-C class message send"); 309 OID = ObjTy->getInterface(); 310 assert(OID && "Invalid Objective-C class message send"); 311 Receiver = Runtime.GetClass(Builder, OID); 312 isClassMessage = true; 313 break; 314 } 315 316 case ObjCMessageExpr::SuperInstance: 317 ReceiverType = E->getSuperType(); 318 Receiver = LoadObjCSelf(); 319 isSuperMessage = true; 320 break; 321 322 case ObjCMessageExpr::SuperClass: 323 ReceiverType = E->getSuperType(); 324 Receiver = LoadObjCSelf(); 325 isSuperMessage = true; 326 isClassMessage = true; 327 break; 328 } 329 330 if (retainSelf) 331 Receiver = EmitARCRetainNonBlock(Receiver); 332 333 // In ARC, we sometimes want to "extend the lifetime" 334 // (i.e. retain+autorelease) of receivers of returns-inner-pointer 335 // messages. 336 if (getLangOpts().ObjCAutoRefCount && method && 337 method->hasAttr<ObjCReturnsInnerPointerAttr>() && 338 shouldExtendReceiverForInnerPointerMessage(E)) 339 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver); 340 341 QualType ResultType = 342 method ? method->getResultType() : E->getType(); 343 344 CallArgList Args; 345 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end()); 346 347 // For delegate init calls in ARC, do an unsafe store of null into 348 // self. This represents the call taking direct ownership of that 349 // value. We have to do this after emitting the other call 350 // arguments because they might also reference self, but we don't 351 // have to worry about any of them modifying self because that would 352 // be an undefined read and write of an object in unordered 353 // expressions. 354 if (isDelegateInit) { 355 assert(getLangOpts().ObjCAutoRefCount && 356 "delegate init calls should only be marked in ARC"); 357 358 // Do an unsafe store of null into self. 359 llvm::Value *selfAddr = 360 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()]; 361 assert(selfAddr && "no self entry for a delegate init call?"); 362 363 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr); 364 } 365 366 RValue result; 367 if (isSuperMessage) { 368 // super is only valid in an Objective-C method 369 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 370 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext()); 371 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType, 372 E->getSelector(), 373 OMD->getClassInterface(), 374 isCategoryImpl, 375 Receiver, 376 isClassMessage, 377 Args, 378 method); 379 } else { 380 result = Runtime.GenerateMessageSend(*this, Return, ResultType, 381 E->getSelector(), 382 Receiver, Args, OID, 383 method); 384 } 385 386 // For delegate init calls in ARC, implicitly store the result of 387 // the call back into self. This takes ownership of the value. 388 if (isDelegateInit) { 389 llvm::Value *selfAddr = 390 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()]; 391 llvm::Value *newSelf = result.getScalarVal(); 392 393 // The delegate return type isn't necessarily a matching type; in 394 // fact, it's quite likely to be 'id'. 395 llvm::Type *selfTy = 396 cast<llvm::PointerType>(selfAddr->getType())->getElementType(); 397 newSelf = Builder.CreateBitCast(newSelf, selfTy); 398 399 Builder.CreateStore(newSelf, selfAddr); 400 } 401 402 return AdjustRelatedResultType(*this, E, method, result); 403 } 404 405 namespace { 406 struct FinishARCDealloc : EHScopeStack::Cleanup { 407 void Emit(CodeGenFunction &CGF, Flags flags) { 408 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl); 409 410 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext()); 411 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 412 if (!iface->getSuperClass()) return; 413 414 bool isCategory = isa<ObjCCategoryImplDecl>(impl); 415 416 // Call [super dealloc] if we have a superclass. 417 llvm::Value *self = CGF.LoadObjCSelf(); 418 419 CallArgList args; 420 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(), 421 CGF.getContext().VoidTy, 422 method->getSelector(), 423 iface, 424 isCategory, 425 self, 426 /*is class msg*/ false, 427 args, 428 method); 429 } 430 }; 431 } 432 433 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates 434 /// the LLVM function and sets the other context used by 435 /// CodeGenFunction. 436 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD, 437 const ObjCContainerDecl *CD, 438 SourceLocation StartLoc) { 439 FunctionArgList args; 440 // Check if we should generate debug info for this method. 441 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>()) 442 DebugInfo = CGM.getModuleDebugInfo(); 443 444 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD); 445 446 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD); 447 CGM.SetInternalFunctionAttributes(OMD, Fn, FI); 448 449 args.push_back(OMD->getSelfDecl()); 450 args.push_back(OMD->getCmdDecl()); 451 452 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(), 453 E = OMD->param_end(); PI != E; ++PI) 454 args.push_back(*PI); 455 456 CurGD = OMD; 457 458 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc); 459 460 // In ARC, certain methods get an extra cleanup. 461 if (CGM.getLangOpts().ObjCAutoRefCount && 462 OMD->isInstanceMethod() && 463 OMD->getSelector().isUnarySelector()) { 464 const IdentifierInfo *ident = 465 OMD->getSelector().getIdentifierInfoForSlot(0); 466 if (ident->isStr("dealloc")) 467 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind()); 468 } 469 } 470 471 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF, 472 LValue lvalue, QualType type); 473 474 /// Generate an Objective-C method. An Objective-C method is a C function with 475 /// its pointer, name, and types registered in the class struture. 476 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) { 477 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart()); 478 EmitStmt(OMD->getBody()); 479 FinishFunction(OMD->getBodyRBrace()); 480 } 481 482 /// emitStructGetterCall - Call the runtime function to load a property 483 /// into the return value slot. 484 static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar, 485 bool isAtomic, bool hasStrong) { 486 ASTContext &Context = CGF.getContext(); 487 488 llvm::Value *src = 489 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), 490 ivar, 0).getAddress(); 491 492 // objc_copyStruct (ReturnValue, &structIvar, 493 // sizeof (Type of Ivar), isAtomic, false); 494 CallArgList args; 495 496 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy); 497 args.add(RValue::get(dest), Context.VoidPtrTy); 498 499 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy); 500 args.add(RValue::get(src), Context.VoidPtrTy); 501 502 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType()); 503 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType()); 504 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy); 505 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy); 506 507 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction(); 508 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Context.VoidTy, args, 509 FunctionType::ExtInfo(), 510 RequiredArgs::All), 511 fn, ReturnValueSlot(), args); 512 } 513 514 /// Determine whether the given architecture supports unaligned atomic 515 /// accesses. They don't have to be fast, just faster than a function 516 /// call and a mutex. 517 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) { 518 // FIXME: Allow unaligned atomic load/store on x86. (It is not 519 // currently supported by the backend.) 520 return 0; 521 } 522 523 /// Return the maximum size that permits atomic accesses for the given 524 /// architecture. 525 static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM, 526 llvm::Triple::ArchType arch) { 527 // ARM has 8-byte atomic accesses, but it's not clear whether we 528 // want to rely on them here. 529 530 // In the default case, just assume that any size up to a pointer is 531 // fine given adequate alignment. 532 return CharUnits::fromQuantity(CGM.PointerSizeInBytes); 533 } 534 535 namespace { 536 class PropertyImplStrategy { 537 public: 538 enum StrategyKind { 539 /// The 'native' strategy is to use the architecture's provided 540 /// reads and writes. 541 Native, 542 543 /// Use objc_setProperty and objc_getProperty. 544 GetSetProperty, 545 546 /// Use objc_setProperty for the setter, but use expression 547 /// evaluation for the getter. 548 SetPropertyAndExpressionGet, 549 550 /// Use objc_copyStruct. 551 CopyStruct, 552 553 /// The 'expression' strategy is to emit normal assignment or 554 /// lvalue-to-rvalue expressions. 555 Expression 556 }; 557 558 StrategyKind getKind() const { return StrategyKind(Kind); } 559 560 bool hasStrongMember() const { return HasStrong; } 561 bool isAtomic() const { return IsAtomic; } 562 bool isCopy() const { return IsCopy; } 563 564 CharUnits getIvarSize() const { return IvarSize; } 565 CharUnits getIvarAlignment() const { return IvarAlignment; } 566 567 PropertyImplStrategy(CodeGenModule &CGM, 568 const ObjCPropertyImplDecl *propImpl); 569 570 private: 571 unsigned Kind : 8; 572 unsigned IsAtomic : 1; 573 unsigned IsCopy : 1; 574 unsigned HasStrong : 1; 575 576 CharUnits IvarSize; 577 CharUnits IvarAlignment; 578 }; 579 } 580 581 /// Pick an implementation strategy for the the given property synthesis. 582 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM, 583 const ObjCPropertyImplDecl *propImpl) { 584 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 585 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind(); 586 587 IsCopy = (setterKind == ObjCPropertyDecl::Copy); 588 IsAtomic = prop->isAtomic(); 589 HasStrong = false; // doesn't matter here. 590 591 // Evaluate the ivar's size and alignment. 592 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 593 QualType ivarType = ivar->getType(); 594 llvm::tie(IvarSize, IvarAlignment) 595 = CGM.getContext().getTypeInfoInChars(ivarType); 596 597 // If we have a copy property, we always have to use getProperty/setProperty. 598 // TODO: we could actually use setProperty and an expression for non-atomics. 599 if (IsCopy) { 600 Kind = GetSetProperty; 601 return; 602 } 603 604 // Handle retain. 605 if (setterKind == ObjCPropertyDecl::Retain) { 606 // In GC-only, there's nothing special that needs to be done. 607 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { 608 // fallthrough 609 610 // In ARC, if the property is non-atomic, use expression emission, 611 // which translates to objc_storeStrong. This isn't required, but 612 // it's slightly nicer. 613 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) { 614 Kind = Expression; 615 return; 616 617 // Otherwise, we need to at least use setProperty. However, if 618 // the property isn't atomic, we can use normal expression 619 // emission for the getter. 620 } else if (!IsAtomic) { 621 Kind = SetPropertyAndExpressionGet; 622 return; 623 624 // Otherwise, we have to use both setProperty and getProperty. 625 } else { 626 Kind = GetSetProperty; 627 return; 628 } 629 } 630 631 // If we're not atomic, just use expression accesses. 632 if (!IsAtomic) { 633 Kind = Expression; 634 return; 635 } 636 637 // Properties on bitfield ivars need to be emitted using expression 638 // accesses even if they're nominally atomic. 639 if (ivar->isBitField()) { 640 Kind = Expression; 641 return; 642 } 643 644 // GC-qualified or ARC-qualified ivars need to be emitted as 645 // expressions. This actually works out to being atomic anyway, 646 // except for ARC __strong, but that should trigger the above code. 647 if (ivarType.hasNonTrivialObjCLifetime() || 648 (CGM.getLangOpts().getGC() && 649 CGM.getContext().getObjCGCAttrKind(ivarType))) { 650 Kind = Expression; 651 return; 652 } 653 654 // Compute whether the ivar has strong members. 655 if (CGM.getLangOpts().getGC()) 656 if (const RecordType *recordType = ivarType->getAs<RecordType>()) 657 HasStrong = recordType->getDecl()->hasObjectMember(); 658 659 // We can never access structs with object members with a native 660 // access, because we need to use write barriers. This is what 661 // objc_copyStruct is for. 662 if (HasStrong) { 663 Kind = CopyStruct; 664 return; 665 } 666 667 // Otherwise, this is target-dependent and based on the size and 668 // alignment of the ivar. 669 670 // If the size of the ivar is not a power of two, give up. We don't 671 // want to get into the business of doing compare-and-swaps. 672 if (!IvarSize.isPowerOfTwo()) { 673 Kind = CopyStruct; 674 return; 675 } 676 677 llvm::Triple::ArchType arch = 678 CGM.getContext().getTargetInfo().getTriple().getArch(); 679 680 // Most architectures require memory to fit within a single cache 681 // line, so the alignment has to be at least the size of the access. 682 // Otherwise we have to grab a lock. 683 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) { 684 Kind = CopyStruct; 685 return; 686 } 687 688 // If the ivar's size exceeds the architecture's maximum atomic 689 // access size, we have to use CopyStruct. 690 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) { 691 Kind = CopyStruct; 692 return; 693 } 694 695 // Otherwise, we can use native loads and stores. 696 Kind = Native; 697 } 698 699 /// GenerateObjCGetter - Generate an Objective-C property getter 700 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize 701 /// is illegal within a category. 702 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP, 703 const ObjCPropertyImplDecl *PID) { 704 llvm::Constant *AtomicHelperFn = 705 GenerateObjCAtomicGetterCopyHelperFunction(PID); 706 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 707 ObjCMethodDecl *OMD = PD->getGetterMethodDecl(); 708 assert(OMD && "Invalid call to generate getter (empty method)"); 709 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart()); 710 711 generateObjCGetterBody(IMP, PID, AtomicHelperFn); 712 713 FinishFunction(); 714 } 715 716 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) { 717 const Expr *getter = propImpl->getGetterCXXConstructor(); 718 if (!getter) return true; 719 720 // Sema only makes only of these when the ivar has a C++ class type, 721 // so the form is pretty constrained. 722 723 // If the property has a reference type, we might just be binding a 724 // reference, in which case the result will be a gl-value. We should 725 // treat this as a non-trivial operation. 726 if (getter->isGLValue()) 727 return false; 728 729 // If we selected a trivial copy-constructor, we're okay. 730 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter)) 731 return (construct->getConstructor()->isTrivial()); 732 733 // The constructor might require cleanups (in which case it's never 734 // trivial). 735 assert(isa<ExprWithCleanups>(getter)); 736 return false; 737 } 738 739 /// emitCPPObjectAtomicGetterCall - Call the runtime function to 740 /// copy the ivar into the resturn slot. 741 static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF, 742 llvm::Value *returnAddr, 743 ObjCIvarDecl *ivar, 744 llvm::Constant *AtomicHelperFn) { 745 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar, 746 // AtomicHelperFn); 747 CallArgList args; 748 749 // The 1st argument is the return Slot. 750 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy); 751 752 // The 2nd argument is the address of the ivar. 753 llvm::Value *ivarAddr = 754 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 755 CGF.LoadObjCSelf(), ivar, 0).getAddress(); 756 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 757 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 758 759 // Third argument is the helper function. 760 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); 761 762 llvm::Value *copyCppAtomicObjectFn = 763 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction(); 764 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args, 765 FunctionType::ExtInfo(), 766 RequiredArgs::All), 767 copyCppAtomicObjectFn, ReturnValueSlot(), args); 768 } 769 770 void 771 CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 772 const ObjCPropertyImplDecl *propImpl, 773 llvm::Constant *AtomicHelperFn) { 774 // If there's a non-trivial 'get' expression, we just have to emit that. 775 if (!hasTrivialGetExpr(propImpl)) { 776 if (!AtomicHelperFn) { 777 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(), 778 /*nrvo*/ 0); 779 EmitReturnStmt(ret); 780 } 781 else { 782 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 783 emitCPPObjectAtomicGetterCall(*this, ReturnValue, 784 ivar, AtomicHelperFn); 785 } 786 return; 787 } 788 789 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 790 QualType propType = prop->getType(); 791 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl(); 792 793 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 794 795 // Pick an implementation strategy. 796 PropertyImplStrategy strategy(CGM, propImpl); 797 switch (strategy.getKind()) { 798 case PropertyImplStrategy::Native: { 799 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0); 800 801 // Currently, all atomic accesses have to be through integer 802 // types, so there's no point in trying to pick a prettier type. 803 llvm::Type *bitcastType = 804 llvm::Type::getIntNTy(getLLVMContext(), 805 getContext().toBits(strategy.getIvarSize())); 806 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay 807 808 // Perform an atomic load. This does not impose ordering constraints. 809 llvm::Value *ivarAddr = LV.getAddress(); 810 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType); 811 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load"); 812 load->setAlignment(strategy.getIvarAlignment().getQuantity()); 813 load->setAtomic(llvm::Unordered); 814 815 // Store that value into the return address. Doing this with a 816 // bitcast is likely to produce some pretty ugly IR, but it's not 817 // the *most* terrible thing in the world. 818 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType)); 819 820 // Make sure we don't do an autorelease. 821 AutoreleaseResult = false; 822 return; 823 } 824 825 case PropertyImplStrategy::GetSetProperty: { 826 llvm::Value *getPropertyFn = 827 CGM.getObjCRuntime().GetPropertyGetFunction(); 828 if (!getPropertyFn) { 829 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy"); 830 return; 831 } 832 833 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true). 834 // FIXME: Can't this be simpler? This might even be worse than the 835 // corresponding gcc code. 836 llvm::Value *cmd = 837 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd"); 838 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy); 839 llvm::Value *ivarOffset = 840 EmitIvarOffset(classImpl->getClassInterface(), ivar); 841 842 CallArgList args; 843 args.add(RValue::get(self), getContext().getObjCIdType()); 844 args.add(RValue::get(cmd), getContext().getObjCSelType()); 845 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 846 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())), 847 getContext().BoolTy); 848 849 // FIXME: We shouldn't need to get the function info here, the 850 // runtime already should have computed it to build the function. 851 RValue RV = EmitCall(getTypes().arrangeFunctionCall(propType, args, 852 FunctionType::ExtInfo(), 853 RequiredArgs::All), 854 getPropertyFn, ReturnValueSlot(), args); 855 856 // We need to fix the type here. Ivars with copy & retain are 857 // always objects so we don't need to worry about complex or 858 // aggregates. 859 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(), 860 getTypes().ConvertType(propType))); 861 862 EmitReturnOfRValue(RV, propType); 863 864 // objc_getProperty does an autorelease, so we should suppress ours. 865 AutoreleaseResult = false; 866 867 return; 868 } 869 870 case PropertyImplStrategy::CopyStruct: 871 emitStructGetterCall(*this, ivar, strategy.isAtomic(), 872 strategy.hasStrongMember()); 873 return; 874 875 case PropertyImplStrategy::Expression: 876 case PropertyImplStrategy::SetPropertyAndExpressionGet: { 877 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0); 878 879 QualType ivarType = ivar->getType(); 880 if (ivarType->isAnyComplexType()) { 881 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(), 882 LV.isVolatileQualified()); 883 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified()); 884 } else if (hasAggregateLLVMType(ivarType)) { 885 // The return value slot is guaranteed to not be aliased, but 886 // that's not necessarily the same as "on the stack", so 887 // we still potentially need objc_memmove_collectable. 888 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType, 889 /*volatile*/ false, 0, /*destIsCompleteObject*/ true); 890 } else { 891 llvm::Value *value; 892 if (propType->isReferenceType()) { 893 value = LV.getAddress(); 894 } else { 895 // We want to load and autoreleaseReturnValue ARC __weak ivars. 896 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 897 value = emitARCRetainLoadOfScalar(*this, LV, ivarType); 898 899 // Otherwise we want to do a simple load, suppressing the 900 // final autorelease. 901 } else { 902 value = EmitLoadOfLValue(LV).getScalarVal(); 903 AutoreleaseResult = false; 904 } 905 906 value = Builder.CreateBitCast(value, ConvertType(propType)); 907 } 908 909 EmitReturnOfRValue(RValue::get(value), propType); 910 } 911 return; 912 } 913 914 } 915 llvm_unreachable("bad @property implementation strategy!"); 916 } 917 918 /// emitStructSetterCall - Call the runtime function to store the value 919 /// from the first formal parameter into the given ivar. 920 static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, 921 ObjCIvarDecl *ivar) { 922 // objc_copyStruct (&structIvar, &Arg, 923 // sizeof (struct something), true, false); 924 CallArgList args; 925 926 // The first argument is the address of the ivar. 927 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 928 CGF.LoadObjCSelf(), ivar, 0) 929 .getAddress(); 930 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 931 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 932 933 // The second argument is the address of the parameter variable. 934 ParmVarDecl *argVar = *OMD->param_begin(); 935 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), 936 VK_LValue, SourceLocation()); 937 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress(); 938 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); 939 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); 940 941 // The third argument is the sizeof the type. 942 llvm::Value *size = 943 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType())); 944 args.add(RValue::get(size), CGF.getContext().getSizeType()); 945 946 // The fourth argument is the 'isAtomic' flag. 947 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy); 948 949 // The fifth argument is the 'hasStrong' flag. 950 // FIXME: should this really always be false? 951 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy); 952 953 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction(); 954 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args, 955 FunctionType::ExtInfo(), 956 RequiredArgs::All), 957 copyStructFn, ReturnValueSlot(), args); 958 } 959 960 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store 961 /// the value from the first formal parameter into the given ivar, using 962 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment. 963 static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, 964 ObjCMethodDecl *OMD, 965 ObjCIvarDecl *ivar, 966 llvm::Constant *AtomicHelperFn) { 967 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg, 968 // AtomicHelperFn); 969 CallArgList args; 970 971 // The first argument is the address of the ivar. 972 llvm::Value *ivarAddr = 973 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 974 CGF.LoadObjCSelf(), ivar, 0).getAddress(); 975 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 976 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 977 978 // The second argument is the address of the parameter variable. 979 ParmVarDecl *argVar = *OMD->param_begin(); 980 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), 981 VK_LValue, SourceLocation()); 982 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress(); 983 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); 984 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); 985 986 // Third argument is the helper function. 987 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); 988 989 llvm::Value *copyCppAtomicObjectFn = 990 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction(); 991 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args, 992 FunctionType::ExtInfo(), 993 RequiredArgs::All), 994 copyCppAtomicObjectFn, ReturnValueSlot(), args); 995 996 997 } 998 999 1000 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) { 1001 Expr *setter = PID->getSetterCXXAssignment(); 1002 if (!setter) return true; 1003 1004 // Sema only makes only of these when the ivar has a C++ class type, 1005 // so the form is pretty constrained. 1006 1007 // An operator call is trivial if the function it calls is trivial. 1008 // This also implies that there's nothing non-trivial going on with 1009 // the arguments, because operator= can only be trivial if it's a 1010 // synthesized assignment operator and therefore both parameters are 1011 // references. 1012 if (CallExpr *call = dyn_cast<CallExpr>(setter)) { 1013 if (const FunctionDecl *callee 1014 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl())) 1015 if (callee->isTrivial()) 1016 return true; 1017 return false; 1018 } 1019 1020 assert(isa<ExprWithCleanups>(setter)); 1021 return false; 1022 } 1023 1024 static bool UseOptimizedSetter(CodeGenModule &CGM) { 1025 if (CGM.getLangOpts().getGC() != LangOptions::NonGC) 1026 return false; 1027 const TargetInfo &Target = CGM.getContext().getTargetInfo(); 1028 1029 if (Target.getPlatformName() != "macosx") 1030 return false; 1031 1032 return Target.getPlatformMinVersion() >= VersionTuple(10, 8); 1033 } 1034 1035 void 1036 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1037 const ObjCPropertyImplDecl *propImpl, 1038 llvm::Constant *AtomicHelperFn) { 1039 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 1040 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 1041 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl(); 1042 1043 // Just use the setter expression if Sema gave us one and it's 1044 // non-trivial. 1045 if (!hasTrivialSetExpr(propImpl)) { 1046 if (!AtomicHelperFn) 1047 // If non-atomic, assignment is called directly. 1048 EmitStmt(propImpl->getSetterCXXAssignment()); 1049 else 1050 // If atomic, assignment is called via a locking api. 1051 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar, 1052 AtomicHelperFn); 1053 return; 1054 } 1055 1056 PropertyImplStrategy strategy(CGM, propImpl); 1057 switch (strategy.getKind()) { 1058 case PropertyImplStrategy::Native: { 1059 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()]; 1060 1061 LValue ivarLValue = 1062 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0); 1063 llvm::Value *ivarAddr = ivarLValue.getAddress(); 1064 1065 // Currently, all atomic accesses have to be through integer 1066 // types, so there's no point in trying to pick a prettier type. 1067 llvm::Type *bitcastType = 1068 llvm::Type::getIntNTy(getLLVMContext(), 1069 getContext().toBits(strategy.getIvarSize())); 1070 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay 1071 1072 // Cast both arguments to the chosen operation type. 1073 argAddr = Builder.CreateBitCast(argAddr, bitcastType); 1074 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType); 1075 1076 // This bitcast load is likely to cause some nasty IR. 1077 llvm::Value *load = Builder.CreateLoad(argAddr); 1078 1079 // Perform an atomic store. There are no memory ordering requirements. 1080 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr); 1081 store->setAlignment(strategy.getIvarAlignment().getQuantity()); 1082 store->setAtomic(llvm::Unordered); 1083 return; 1084 } 1085 1086 case PropertyImplStrategy::GetSetProperty: 1087 case PropertyImplStrategy::SetPropertyAndExpressionGet: { 1088 1089 llvm::Value *setOptimizedPropertyFn = 0; 1090 llvm::Value *setPropertyFn = 0; 1091 if (UseOptimizedSetter(CGM)) { 1092 // 10.8 code and GC is off 1093 setOptimizedPropertyFn = 1094 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(strategy.isAtomic(), 1095 strategy.isCopy()); 1096 if (!setOptimizedPropertyFn) { 1097 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI"); 1098 return; 1099 } 1100 } 1101 else { 1102 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction(); 1103 if (!setPropertyFn) { 1104 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy"); 1105 return; 1106 } 1107 } 1108 1109 // Emit objc_setProperty((id) self, _cmd, offset, arg, 1110 // <is-atomic>, <is-copy>). 1111 llvm::Value *cmd = 1112 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]); 1113 llvm::Value *self = 1114 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy); 1115 llvm::Value *ivarOffset = 1116 EmitIvarOffset(classImpl->getClassInterface(), ivar); 1117 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()]; 1118 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy); 1119 1120 CallArgList args; 1121 args.add(RValue::get(self), getContext().getObjCIdType()); 1122 args.add(RValue::get(cmd), getContext().getObjCSelType()); 1123 if (setOptimizedPropertyFn) { 1124 args.add(RValue::get(arg), getContext().getObjCIdType()); 1125 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 1126 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args, 1127 FunctionType::ExtInfo(), 1128 RequiredArgs::All), 1129 setOptimizedPropertyFn, ReturnValueSlot(), args); 1130 } else { 1131 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 1132 args.add(RValue::get(arg), getContext().getObjCIdType()); 1133 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())), 1134 getContext().BoolTy); 1135 args.add(RValue::get(Builder.getInt1(strategy.isCopy())), 1136 getContext().BoolTy); 1137 // FIXME: We shouldn't need to get the function info here, the runtime 1138 // already should have computed it to build the function. 1139 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args, 1140 FunctionType::ExtInfo(), 1141 RequiredArgs::All), 1142 setPropertyFn, ReturnValueSlot(), args); 1143 } 1144 1145 return; 1146 } 1147 1148 case PropertyImplStrategy::CopyStruct: 1149 emitStructSetterCall(*this, setterMethod, ivar); 1150 return; 1151 1152 case PropertyImplStrategy::Expression: 1153 break; 1154 } 1155 1156 // Otherwise, fake up some ASTs and emit a normal assignment. 1157 ValueDecl *selfDecl = setterMethod->getSelfDecl(); 1158 DeclRefExpr self(selfDecl, false, selfDecl->getType(), 1159 VK_LValue, SourceLocation()); 1160 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, 1161 selfDecl->getType(), CK_LValueToRValue, &self, 1162 VK_RValue); 1163 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(), 1164 SourceLocation(), &selfLoad, true, true); 1165 1166 ParmVarDecl *argDecl = *setterMethod->param_begin(); 1167 QualType argType = argDecl->getType().getNonReferenceType(); 1168 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation()); 1169 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack, 1170 argType.getUnqualifiedType(), CK_LValueToRValue, 1171 &arg, VK_RValue); 1172 1173 // The property type can differ from the ivar type in some situations with 1174 // Objective-C pointer types, we can always bit cast the RHS in these cases. 1175 // The following absurdity is just to ensure well-formed IR. 1176 CastKind argCK = CK_NoOp; 1177 if (ivarRef.getType()->isObjCObjectPointerType()) { 1178 if (argLoad.getType()->isObjCObjectPointerType()) 1179 argCK = CK_BitCast; 1180 else if (argLoad.getType()->isBlockPointerType()) 1181 argCK = CK_BlockPointerToObjCPointerCast; 1182 else 1183 argCK = CK_CPointerToObjCPointerCast; 1184 } else if (ivarRef.getType()->isBlockPointerType()) { 1185 if (argLoad.getType()->isBlockPointerType()) 1186 argCK = CK_BitCast; 1187 else 1188 argCK = CK_AnyPointerToBlockPointerCast; 1189 } else if (ivarRef.getType()->isPointerType()) { 1190 argCK = CK_BitCast; 1191 } 1192 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, 1193 ivarRef.getType(), argCK, &argLoad, 1194 VK_RValue); 1195 Expr *finalArg = &argLoad; 1196 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(), 1197 argLoad.getType())) 1198 finalArg = &argCast; 1199 1200 1201 BinaryOperator assign(&ivarRef, finalArg, BO_Assign, 1202 ivarRef.getType(), VK_RValue, OK_Ordinary, 1203 SourceLocation()); 1204 EmitStmt(&assign); 1205 } 1206 1207 /// GenerateObjCSetter - Generate an Objective-C property setter 1208 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize 1209 /// is illegal within a category. 1210 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, 1211 const ObjCPropertyImplDecl *PID) { 1212 llvm::Constant *AtomicHelperFn = 1213 GenerateObjCAtomicSetterCopyHelperFunction(PID); 1214 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1215 ObjCMethodDecl *OMD = PD->getSetterMethodDecl(); 1216 assert(OMD && "Invalid call to generate setter (empty method)"); 1217 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart()); 1218 1219 generateObjCSetterBody(IMP, PID, AtomicHelperFn); 1220 1221 FinishFunction(); 1222 } 1223 1224 namespace { 1225 struct DestroyIvar : EHScopeStack::Cleanup { 1226 private: 1227 llvm::Value *addr; 1228 const ObjCIvarDecl *ivar; 1229 CodeGenFunction::Destroyer *destroyer; 1230 bool useEHCleanupForArray; 1231 public: 1232 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar, 1233 CodeGenFunction::Destroyer *destroyer, 1234 bool useEHCleanupForArray) 1235 : addr(addr), ivar(ivar), destroyer(destroyer), 1236 useEHCleanupForArray(useEHCleanupForArray) {} 1237 1238 void Emit(CodeGenFunction &CGF, Flags flags) { 1239 LValue lvalue 1240 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0); 1241 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer, 1242 flags.isForNormalCleanup() && useEHCleanupForArray); 1243 } 1244 }; 1245 } 1246 1247 /// Like CodeGenFunction::destroyARCStrong, but do it with a call. 1248 static void destroyARCStrongWithStore(CodeGenFunction &CGF, 1249 llvm::Value *addr, 1250 QualType type) { 1251 llvm::Value *null = getNullForVariable(addr); 1252 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true); 1253 } 1254 1255 static void emitCXXDestructMethod(CodeGenFunction &CGF, 1256 ObjCImplementationDecl *impl) { 1257 CodeGenFunction::RunCleanupsScope scope(CGF); 1258 1259 llvm::Value *self = CGF.LoadObjCSelf(); 1260 1261 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 1262 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 1263 ivar; ivar = ivar->getNextIvar()) { 1264 QualType type = ivar->getType(); 1265 1266 // Check whether the ivar is a destructible type. 1267 QualType::DestructionKind dtorKind = type.isDestructedType(); 1268 if (!dtorKind) continue; 1269 1270 CodeGenFunction::Destroyer *destroyer = 0; 1271 1272 // Use a call to objc_storeStrong to destroy strong ivars, for the 1273 // general benefit of the tools. 1274 if (dtorKind == QualType::DK_objc_strong_lifetime) { 1275 destroyer = destroyARCStrongWithStore; 1276 1277 // Otherwise use the default for the destruction kind. 1278 } else { 1279 destroyer = CGF.getDestroyer(dtorKind); 1280 } 1281 1282 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind); 1283 1284 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer, 1285 cleanupKind & EHCleanup); 1286 } 1287 1288 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?"); 1289 } 1290 1291 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1292 ObjCMethodDecl *MD, 1293 bool ctor) { 1294 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface()); 1295 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart()); 1296 1297 // Emit .cxx_construct. 1298 if (ctor) { 1299 // Suppress the final autorelease in ARC. 1300 AutoreleaseResult = false; 1301 1302 SmallVector<CXXCtorInitializer *, 8> IvarInitializers; 1303 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(), 1304 E = IMP->init_end(); B != E; ++B) { 1305 CXXCtorInitializer *IvarInit = (*B); 1306 FieldDecl *Field = IvarInit->getAnyMember(); 1307 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); 1308 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), 1309 LoadObjCSelf(), Ivar, 0); 1310 EmitAggExpr(IvarInit->getInit(), 1311 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed, 1312 AggValueSlot::DoesNotNeedGCBarriers, 1313 AggValueSlot::IsNotAliased, 1314 AggValueSlot::IsCompleteObject)); 1315 } 1316 // constructor returns 'self'. 1317 CodeGenTypes &Types = CGM.getTypes(); 1318 QualType IdTy(CGM.getContext().getObjCIdType()); 1319 llvm::Value *SelfAsId = 1320 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 1321 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy); 1322 1323 // Emit .cxx_destruct. 1324 } else { 1325 emitCXXDestructMethod(*this, IMP); 1326 } 1327 FinishFunction(); 1328 } 1329 1330 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) { 1331 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(); 1332 it++; it++; 1333 const ABIArgInfo &AI = it->info; 1334 // FIXME. Is this sufficient check? 1335 return (AI.getKind() == ABIArgInfo::Indirect); 1336 } 1337 1338 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) { 1339 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) 1340 return false; 1341 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>()) 1342 return FDTTy->getDecl()->hasObjectMember(); 1343 return false; 1344 } 1345 1346 llvm::Value *CodeGenFunction::LoadObjCSelf() { 1347 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 1348 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self"); 1349 } 1350 1351 QualType CodeGenFunction::TypeOfSelfObject() { 1352 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 1353 ImplicitParamDecl *selfDecl = OMD->getSelfDecl(); 1354 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>( 1355 getContext().getCanonicalType(selfDecl->getType())); 1356 return PTy->getPointeeType(); 1357 } 1358 1359 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ 1360 llvm::Constant *EnumerationMutationFn = 1361 CGM.getObjCRuntime().EnumerationMutationFunction(); 1362 1363 if (!EnumerationMutationFn) { 1364 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime"); 1365 return; 1366 } 1367 1368 CGDebugInfo *DI = getDebugInfo(); 1369 if (DI) 1370 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin()); 1371 1372 // The local variable comes into scope immediately. 1373 AutoVarEmission variable = AutoVarEmission::invalid(); 1374 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) 1375 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl())); 1376 1377 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end"); 1378 1379 // Fast enumeration state. 1380 QualType StateTy = CGM.getObjCFastEnumerationStateType(); 1381 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr"); 1382 EmitNullInitialization(StatePtr, StateTy); 1383 1384 // Number of elements in the items array. 1385 static const unsigned NumItems = 16; 1386 1387 // Fetch the countByEnumeratingWithState:objects:count: selector. 1388 IdentifierInfo *II[] = { 1389 &CGM.getContext().Idents.get("countByEnumeratingWithState"), 1390 &CGM.getContext().Idents.get("objects"), 1391 &CGM.getContext().Idents.get("count") 1392 }; 1393 Selector FastEnumSel = 1394 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]); 1395 1396 QualType ItemsTy = 1397 getContext().getConstantArrayType(getContext().getObjCIdType(), 1398 llvm::APInt(32, NumItems), 1399 ArrayType::Normal, 0); 1400 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr"); 1401 1402 // Emit the collection pointer. In ARC, we do a retain. 1403 llvm::Value *Collection; 1404 if (getLangOpts().ObjCAutoRefCount) { 1405 Collection = EmitARCRetainScalarExpr(S.getCollection()); 1406 1407 // Enter a cleanup to do the release. 1408 EmitObjCConsumeObject(S.getCollection()->getType(), Collection); 1409 } else { 1410 Collection = EmitScalarExpr(S.getCollection()); 1411 } 1412 1413 // The 'continue' label needs to appear within the cleanup for the 1414 // collection object. 1415 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next"); 1416 1417 // Send it our message: 1418 CallArgList Args; 1419 1420 // The first argument is a temporary of the enumeration-state type. 1421 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy)); 1422 1423 // The second argument is a temporary array with space for NumItems 1424 // pointers. We'll actually be loading elements from the array 1425 // pointer written into the control state; this buffer is so that 1426 // collections that *aren't* backed by arrays can still queue up 1427 // batches of elements. 1428 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy)); 1429 1430 // The third argument is the capacity of that temporary array. 1431 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy); 1432 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems); 1433 Args.add(RValue::get(Count), getContext().UnsignedLongTy); 1434 1435 // Start the enumeration. 1436 RValue CountRV = 1437 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 1438 getContext().UnsignedLongTy, 1439 FastEnumSel, 1440 Collection, Args); 1441 1442 // The initial number of objects that were returned in the buffer. 1443 llvm::Value *initialBufferLimit = CountRV.getScalarVal(); 1444 1445 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty"); 1446 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit"); 1447 1448 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy); 1449 1450 // If the limit pointer was zero to begin with, the collection is 1451 // empty; skip all this. 1452 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), 1453 EmptyBB, LoopInitBB); 1454 1455 // Otherwise, initialize the loop. 1456 EmitBlock(LoopInitBB); 1457 1458 // Save the initial mutations value. This is the value at an 1459 // address that was written into the state object by 1460 // countByEnumeratingWithState:objects:count:. 1461 llvm::Value *StateMutationsPtrPtr = 1462 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr"); 1463 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, 1464 "mutationsptr"); 1465 1466 llvm::Value *initialMutations = 1467 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations"); 1468 1469 // Start looping. This is the point we return to whenever we have a 1470 // fresh, non-empty batch of objects. 1471 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody"); 1472 EmitBlock(LoopBodyBB); 1473 1474 // The current index into the buffer. 1475 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index"); 1476 index->addIncoming(zero, LoopInitBB); 1477 1478 // The current buffer size. 1479 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count"); 1480 count->addIncoming(initialBufferLimit, LoopInitBB); 1481 1482 // Check whether the mutations value has changed from where it was 1483 // at start. StateMutationsPtr should actually be invariant between 1484 // refreshes. 1485 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr"); 1486 llvm::Value *currentMutations 1487 = Builder.CreateLoad(StateMutationsPtr, "statemutations"); 1488 1489 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated"); 1490 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated"); 1491 1492 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations), 1493 WasNotMutatedBB, WasMutatedBB); 1494 1495 // If so, call the enumeration-mutation function. 1496 EmitBlock(WasMutatedBB); 1497 llvm::Value *V = 1498 Builder.CreateBitCast(Collection, 1499 ConvertType(getContext().getObjCIdType())); 1500 CallArgList Args2; 1501 Args2.add(RValue::get(V), getContext().getObjCIdType()); 1502 // FIXME: We shouldn't need to get the function info here, the runtime already 1503 // should have computed it to build the function. 1504 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2, 1505 FunctionType::ExtInfo(), 1506 RequiredArgs::All), 1507 EnumerationMutationFn, ReturnValueSlot(), Args2); 1508 1509 // Otherwise, or if the mutation function returns, just continue. 1510 EmitBlock(WasNotMutatedBB); 1511 1512 // Initialize the element variable. 1513 RunCleanupsScope elementVariableScope(*this); 1514 bool elementIsVariable; 1515 LValue elementLValue; 1516 QualType elementType; 1517 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) { 1518 // Initialize the variable, in case it's a __block variable or something. 1519 EmitAutoVarInit(variable); 1520 1521 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl()); 1522 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(), 1523 VK_LValue, SourceLocation()); 1524 elementLValue = EmitLValue(&tempDRE); 1525 elementType = D->getType(); 1526 elementIsVariable = true; 1527 1528 if (D->isARCPseudoStrong()) 1529 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone); 1530 } else { 1531 elementLValue = LValue(); // suppress warning 1532 elementType = cast<Expr>(S.getElement())->getType(); 1533 elementIsVariable = false; 1534 } 1535 llvm::Type *convertedElementType = ConvertType(elementType); 1536 1537 // Fetch the buffer out of the enumeration state. 1538 // TODO: this pointer should actually be invariant between 1539 // refreshes, which would help us do certain loop optimizations. 1540 llvm::Value *StateItemsPtr = 1541 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr"); 1542 llvm::Value *EnumStateItems = 1543 Builder.CreateLoad(StateItemsPtr, "stateitems"); 1544 1545 // Fetch the value at the current index from the buffer. 1546 llvm::Value *CurrentItemPtr = 1547 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr"); 1548 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr); 1549 1550 // Cast that value to the right type. 1551 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType, 1552 "currentitem"); 1553 1554 // Make sure we have an l-value. Yes, this gets evaluated every 1555 // time through the loop. 1556 if (!elementIsVariable) { 1557 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 1558 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue); 1559 } else { 1560 EmitScalarInit(CurrentItem, elementLValue); 1561 } 1562 1563 // If we do have an element variable, this assignment is the end of 1564 // its initialization. 1565 if (elementIsVariable) 1566 EmitAutoVarCleanups(variable); 1567 1568 // Perform the loop body, setting up break and continue labels. 1569 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody)); 1570 { 1571 RunCleanupsScope Scope(*this); 1572 EmitStmt(S.getBody()); 1573 } 1574 BreakContinueStack.pop_back(); 1575 1576 // Destroy the element variable now. 1577 elementVariableScope.ForceCleanup(); 1578 1579 // Check whether there are more elements. 1580 EmitBlock(AfterBody.getBlock()); 1581 1582 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch"); 1583 1584 // First we check in the local buffer. 1585 llvm::Value *indexPlusOne 1586 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1)); 1587 1588 // If we haven't overrun the buffer yet, we can continue. 1589 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count), 1590 LoopBodyBB, FetchMoreBB); 1591 1592 index->addIncoming(indexPlusOne, AfterBody.getBlock()); 1593 count->addIncoming(count, AfterBody.getBlock()); 1594 1595 // Otherwise, we have to fetch more elements. 1596 EmitBlock(FetchMoreBB); 1597 1598 CountRV = 1599 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 1600 getContext().UnsignedLongTy, 1601 FastEnumSel, 1602 Collection, Args); 1603 1604 // If we got a zero count, we're done. 1605 llvm::Value *refetchCount = CountRV.getScalarVal(); 1606 1607 // (note that the message send might split FetchMoreBB) 1608 index->addIncoming(zero, Builder.GetInsertBlock()); 1609 count->addIncoming(refetchCount, Builder.GetInsertBlock()); 1610 1611 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero), 1612 EmptyBB, LoopBodyBB); 1613 1614 // No more elements. 1615 EmitBlock(EmptyBB); 1616 1617 if (!elementIsVariable) { 1618 // If the element was not a declaration, set it to be null. 1619 1620 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType); 1621 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 1622 EmitStoreThroughLValue(RValue::get(null), elementLValue); 1623 } 1624 1625 if (DI) 1626 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd()); 1627 1628 // Leave the cleanup we entered in ARC. 1629 if (getLangOpts().ObjCAutoRefCount) 1630 PopCleanupBlock(); 1631 1632 EmitBlock(LoopEnd.getBlock()); 1633 } 1634 1635 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) { 1636 CGM.getObjCRuntime().EmitTryStmt(*this, S); 1637 } 1638 1639 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) { 1640 CGM.getObjCRuntime().EmitThrowStmt(*this, S); 1641 } 1642 1643 void CodeGenFunction::EmitObjCAtSynchronizedStmt( 1644 const ObjCAtSynchronizedStmt &S) { 1645 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S); 1646 } 1647 1648 /// Produce the code for a CK_ARCProduceObject. Just does a 1649 /// primitive retain. 1650 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type, 1651 llvm::Value *value) { 1652 return EmitARCRetain(type, value); 1653 } 1654 1655 namespace { 1656 struct CallObjCRelease : EHScopeStack::Cleanup { 1657 CallObjCRelease(llvm::Value *object) : object(object) {} 1658 llvm::Value *object; 1659 1660 void Emit(CodeGenFunction &CGF, Flags flags) { 1661 CGF.EmitARCRelease(object, /*precise*/ true); 1662 } 1663 }; 1664 } 1665 1666 /// Produce the code for a CK_ARCConsumeObject. Does a primitive 1667 /// release at the end of the full-expression. 1668 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type, 1669 llvm::Value *object) { 1670 // If we're in a conditional branch, we need to make the cleanup 1671 // conditional. 1672 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object); 1673 return object; 1674 } 1675 1676 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type, 1677 llvm::Value *value) { 1678 return EmitARCRetainAutorelease(type, value); 1679 } 1680 1681 1682 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM, 1683 llvm::FunctionType *type, 1684 StringRef fnName) { 1685 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName); 1686 1687 // In -fobjc-no-arc-runtime, emit weak references to the runtime 1688 // support library. 1689 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC) 1690 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) 1691 f->setLinkage(llvm::Function::ExternalWeakLinkage); 1692 1693 return fn; 1694 } 1695 1696 /// Perform an operation having the signature 1697 /// i8* (i8*) 1698 /// where a null input causes a no-op and returns null. 1699 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF, 1700 llvm::Value *value, 1701 llvm::Constant *&fn, 1702 StringRef fnName) { 1703 if (isa<llvm::ConstantPointerNull>(value)) return value; 1704 1705 if (!fn) { 1706 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy); 1707 llvm::FunctionType *fnType = 1708 llvm::FunctionType::get(CGF.Int8PtrTy, args, false); 1709 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1710 } 1711 1712 // Cast the argument to 'id'. 1713 llvm::Type *origType = value->getType(); 1714 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy); 1715 1716 // Call the function. 1717 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value); 1718 call->setDoesNotThrow(); 1719 1720 // Cast the result back to the original type. 1721 return CGF.Builder.CreateBitCast(call, origType); 1722 } 1723 1724 /// Perform an operation having the following signature: 1725 /// i8* (i8**) 1726 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, 1727 llvm::Value *addr, 1728 llvm::Constant *&fn, 1729 StringRef fnName) { 1730 if (!fn) { 1731 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy); 1732 llvm::FunctionType *fnType = 1733 llvm::FunctionType::get(CGF.Int8PtrTy, args, false); 1734 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1735 } 1736 1737 // Cast the argument to 'id*'. 1738 llvm::Type *origType = addr->getType(); 1739 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy); 1740 1741 // Call the function. 1742 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr); 1743 call->setDoesNotThrow(); 1744 1745 // Cast the result back to a dereference of the original type. 1746 llvm::Value *result = call; 1747 if (origType != CGF.Int8PtrPtrTy) 1748 result = CGF.Builder.CreateBitCast(result, 1749 cast<llvm::PointerType>(origType)->getElementType()); 1750 1751 return result; 1752 } 1753 1754 /// Perform an operation having the following signature: 1755 /// i8* (i8**, i8*) 1756 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, 1757 llvm::Value *addr, 1758 llvm::Value *value, 1759 llvm::Constant *&fn, 1760 StringRef fnName, 1761 bool ignored) { 1762 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 1763 == value->getType()); 1764 1765 if (!fn) { 1766 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy }; 1767 1768 llvm::FunctionType *fnType 1769 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false); 1770 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1771 } 1772 1773 llvm::Type *origType = value->getType(); 1774 1775 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy); 1776 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy); 1777 1778 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value); 1779 result->setDoesNotThrow(); 1780 1781 if (ignored) return 0; 1782 1783 return CGF.Builder.CreateBitCast(result, origType); 1784 } 1785 1786 /// Perform an operation having the following signature: 1787 /// void (i8**, i8**) 1788 static void emitARCCopyOperation(CodeGenFunction &CGF, 1789 llvm::Value *dst, 1790 llvm::Value *src, 1791 llvm::Constant *&fn, 1792 StringRef fnName) { 1793 assert(dst->getType() == src->getType()); 1794 1795 if (!fn) { 1796 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy); 1797 llvm::FunctionType *fnType 1798 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false); 1799 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1800 } 1801 1802 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy); 1803 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy); 1804 1805 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src); 1806 result->setDoesNotThrow(); 1807 } 1808 1809 /// Produce the code to do a retain. Based on the type, calls one of: 1810 /// call i8* @objc_retain(i8* %value) 1811 /// call i8* @objc_retainBlock(i8* %value) 1812 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) { 1813 if (type->isBlockPointerType()) 1814 return EmitARCRetainBlock(value, /*mandatory*/ false); 1815 else 1816 return EmitARCRetainNonBlock(value); 1817 } 1818 1819 /// Retain the given object, with normal retain semantics. 1820 /// call i8* @objc_retain(i8* %value) 1821 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) { 1822 return emitARCValueOperation(*this, value, 1823 CGM.getARCEntrypoints().objc_retain, 1824 "objc_retain"); 1825 } 1826 1827 /// Retain the given block, with _Block_copy semantics. 1828 /// call i8* @objc_retainBlock(i8* %value) 1829 /// 1830 /// \param mandatory - If false, emit the call with metadata 1831 /// indicating that it's okay for the optimizer to eliminate this call 1832 /// if it can prove that the block never escapes except down the stack. 1833 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value, 1834 bool mandatory) { 1835 llvm::Value *result 1836 = emitARCValueOperation(*this, value, 1837 CGM.getARCEntrypoints().objc_retainBlock, 1838 "objc_retainBlock"); 1839 1840 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to 1841 // tell the optimizer that it doesn't need to do this copy if the 1842 // block doesn't escape, where being passed as an argument doesn't 1843 // count as escaping. 1844 if (!mandatory && isa<llvm::Instruction>(result)) { 1845 llvm::CallInst *call 1846 = cast<llvm::CallInst>(result->stripPointerCasts()); 1847 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock); 1848 1849 SmallVector<llvm::Value*,1> args; 1850 call->setMetadata("clang.arc.copy_on_escape", 1851 llvm::MDNode::get(Builder.getContext(), args)); 1852 } 1853 1854 return result; 1855 } 1856 1857 /// Retain the given object which is the result of a function call. 1858 /// call i8* @objc_retainAutoreleasedReturnValue(i8* %value) 1859 /// 1860 /// Yes, this function name is one character away from a different 1861 /// call with completely different semantics. 1862 llvm::Value * 1863 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) { 1864 // Fetch the void(void) inline asm which marks that we're going to 1865 // retain the autoreleased return value. 1866 llvm::InlineAsm *&marker 1867 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker; 1868 if (!marker) { 1869 StringRef assembly 1870 = CGM.getTargetCodeGenInfo() 1871 .getARCRetainAutoreleasedReturnValueMarker(); 1872 1873 // If we have an empty assembly string, there's nothing to do. 1874 if (assembly.empty()) { 1875 1876 // Otherwise, at -O0, build an inline asm that we're going to call 1877 // in a moment. 1878 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1879 llvm::FunctionType *type = 1880 llvm::FunctionType::get(VoidTy, /*variadic*/false); 1881 1882 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true); 1883 1884 // If we're at -O1 and above, we don't want to litter the code 1885 // with this marker yet, so leave a breadcrumb for the ARC 1886 // optimizer to pick up. 1887 } else { 1888 llvm::NamedMDNode *metadata = 1889 CGM.getModule().getOrInsertNamedMetadata( 1890 "clang.arc.retainAutoreleasedReturnValueMarker"); 1891 assert(metadata->getNumOperands() <= 1); 1892 if (metadata->getNumOperands() == 0) { 1893 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly); 1894 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string)); 1895 } 1896 } 1897 } 1898 1899 // Call the marker asm if we made one, which we do only at -O0. 1900 if (marker) Builder.CreateCall(marker); 1901 1902 return emitARCValueOperation(*this, value, 1903 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue, 1904 "objc_retainAutoreleasedReturnValue"); 1905 } 1906 1907 /// Release the given object. 1908 /// call void @objc_release(i8* %value) 1909 void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) { 1910 if (isa<llvm::ConstantPointerNull>(value)) return; 1911 1912 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release; 1913 if (!fn) { 1914 std::vector<llvm::Type*> args(1, Int8PtrTy); 1915 llvm::FunctionType *fnType = 1916 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 1917 fn = createARCRuntimeFunction(CGM, fnType, "objc_release"); 1918 } 1919 1920 // Cast the argument to 'id'. 1921 value = Builder.CreateBitCast(value, Int8PtrTy); 1922 1923 // Call objc_release. 1924 llvm::CallInst *call = Builder.CreateCall(fn, value); 1925 call->setDoesNotThrow(); 1926 1927 if (!precise) { 1928 SmallVector<llvm::Value*,1> args; 1929 call->setMetadata("clang.imprecise_release", 1930 llvm::MDNode::get(Builder.getContext(), args)); 1931 } 1932 } 1933 1934 /// Store into a strong object. Always calls this: 1935 /// call void @objc_storeStrong(i8** %addr, i8* %value) 1936 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr, 1937 llvm::Value *value, 1938 bool ignored) { 1939 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 1940 == value->getType()); 1941 1942 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong; 1943 if (!fn) { 1944 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy }; 1945 llvm::FunctionType *fnType 1946 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false); 1947 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong"); 1948 } 1949 1950 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy); 1951 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy); 1952 1953 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow(); 1954 1955 if (ignored) return 0; 1956 return value; 1957 } 1958 1959 /// Store into a strong object. Sometimes calls this: 1960 /// call void @objc_storeStrong(i8** %addr, i8* %value) 1961 /// Other times, breaks it down into components. 1962 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst, 1963 llvm::Value *newValue, 1964 bool ignored) { 1965 QualType type = dst.getType(); 1966 bool isBlock = type->isBlockPointerType(); 1967 1968 // Use a store barrier at -O0 unless this is a block type or the 1969 // lvalue is inadequately aligned. 1970 if (shouldUseFusedARCCalls() && 1971 !isBlock && 1972 (dst.getAlignment().isZero() || 1973 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) { 1974 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored); 1975 } 1976 1977 // Otherwise, split it out. 1978 1979 // Retain the new value. 1980 newValue = EmitARCRetain(type, newValue); 1981 1982 // Read the old value. 1983 llvm::Value *oldValue = EmitLoadOfScalar(dst); 1984 1985 // Store. We do this before the release so that any deallocs won't 1986 // see the old value. 1987 EmitStoreOfScalar(newValue, dst); 1988 1989 // Finally, release the old value. 1990 EmitARCRelease(oldValue, /*precise*/ false); 1991 1992 return newValue; 1993 } 1994 1995 /// Autorelease the given object. 1996 /// call i8* @objc_autorelease(i8* %value) 1997 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) { 1998 return emitARCValueOperation(*this, value, 1999 CGM.getARCEntrypoints().objc_autorelease, 2000 "objc_autorelease"); 2001 } 2002 2003 /// Autorelease the given object. 2004 /// call i8* @objc_autoreleaseReturnValue(i8* %value) 2005 llvm::Value * 2006 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) { 2007 return emitARCValueOperation(*this, value, 2008 CGM.getARCEntrypoints().objc_autoreleaseReturnValue, 2009 "objc_autoreleaseReturnValue"); 2010 } 2011 2012 /// Do a fused retain/autorelease of the given object. 2013 /// call i8* @objc_retainAutoreleaseReturnValue(i8* %value) 2014 llvm::Value * 2015 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) { 2016 return emitARCValueOperation(*this, value, 2017 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue, 2018 "objc_retainAutoreleaseReturnValue"); 2019 } 2020 2021 /// Do a fused retain/autorelease of the given object. 2022 /// call i8* @objc_retainAutorelease(i8* %value) 2023 /// or 2024 /// %retain = call i8* @objc_retainBlock(i8* %value) 2025 /// call i8* @objc_autorelease(i8* %retain) 2026 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type, 2027 llvm::Value *value) { 2028 if (!type->isBlockPointerType()) 2029 return EmitARCRetainAutoreleaseNonBlock(value); 2030 2031 if (isa<llvm::ConstantPointerNull>(value)) return value; 2032 2033 llvm::Type *origType = value->getType(); 2034 value = Builder.CreateBitCast(value, Int8PtrTy); 2035 value = EmitARCRetainBlock(value, /*mandatory*/ true); 2036 value = EmitARCAutorelease(value); 2037 return Builder.CreateBitCast(value, origType); 2038 } 2039 2040 /// Do a fused retain/autorelease of the given object. 2041 /// call i8* @objc_retainAutorelease(i8* %value) 2042 llvm::Value * 2043 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) { 2044 return emitARCValueOperation(*this, value, 2045 CGM.getARCEntrypoints().objc_retainAutorelease, 2046 "objc_retainAutorelease"); 2047 } 2048 2049 /// i8* @objc_loadWeak(i8** %addr) 2050 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)). 2051 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) { 2052 return emitARCLoadOperation(*this, addr, 2053 CGM.getARCEntrypoints().objc_loadWeak, 2054 "objc_loadWeak"); 2055 } 2056 2057 /// i8* @objc_loadWeakRetained(i8** %addr) 2058 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) { 2059 return emitARCLoadOperation(*this, addr, 2060 CGM.getARCEntrypoints().objc_loadWeakRetained, 2061 "objc_loadWeakRetained"); 2062 } 2063 2064 /// i8* @objc_storeWeak(i8** %addr, i8* %value) 2065 /// Returns %value. 2066 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr, 2067 llvm::Value *value, 2068 bool ignored) { 2069 return emitARCStoreOperation(*this, addr, value, 2070 CGM.getARCEntrypoints().objc_storeWeak, 2071 "objc_storeWeak", ignored); 2072 } 2073 2074 /// i8* @objc_initWeak(i8** %addr, i8* %value) 2075 /// Returns %value. %addr is known to not have a current weak entry. 2076 /// Essentially equivalent to: 2077 /// *addr = nil; objc_storeWeak(addr, value); 2078 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) { 2079 // If we're initializing to null, just write null to memory; no need 2080 // to get the runtime involved. But don't do this if optimization 2081 // is enabled, because accounting for this would make the optimizer 2082 // much more complicated. 2083 if (isa<llvm::ConstantPointerNull>(value) && 2084 CGM.getCodeGenOpts().OptimizationLevel == 0) { 2085 Builder.CreateStore(value, addr); 2086 return; 2087 } 2088 2089 emitARCStoreOperation(*this, addr, value, 2090 CGM.getARCEntrypoints().objc_initWeak, 2091 "objc_initWeak", /*ignored*/ true); 2092 } 2093 2094 /// void @objc_destroyWeak(i8** %addr) 2095 /// Essentially objc_storeWeak(addr, nil). 2096 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) { 2097 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak; 2098 if (!fn) { 2099 std::vector<llvm::Type*> args(1, Int8PtrPtrTy); 2100 llvm::FunctionType *fnType = 2101 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 2102 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak"); 2103 } 2104 2105 // Cast the argument to 'id*'. 2106 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy); 2107 2108 llvm::CallInst *call = Builder.CreateCall(fn, addr); 2109 call->setDoesNotThrow(); 2110 } 2111 2112 /// void @objc_moveWeak(i8** %dest, i8** %src) 2113 /// Disregards the current value in %dest. Leaves %src pointing to nothing. 2114 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)). 2115 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) { 2116 emitARCCopyOperation(*this, dst, src, 2117 CGM.getARCEntrypoints().objc_moveWeak, 2118 "objc_moveWeak"); 2119 } 2120 2121 /// void @objc_copyWeak(i8** %dest, i8** %src) 2122 /// Disregards the current value in %dest. Essentially 2123 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src))) 2124 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) { 2125 emitARCCopyOperation(*this, dst, src, 2126 CGM.getARCEntrypoints().objc_copyWeak, 2127 "objc_copyWeak"); 2128 } 2129 2130 /// Produce the code to do a objc_autoreleasepool_push. 2131 /// call i8* @objc_autoreleasePoolPush(void) 2132 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() { 2133 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush; 2134 if (!fn) { 2135 llvm::FunctionType *fnType = 2136 llvm::FunctionType::get(Int8PtrTy, false); 2137 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush"); 2138 } 2139 2140 llvm::CallInst *call = Builder.CreateCall(fn); 2141 call->setDoesNotThrow(); 2142 2143 return call; 2144 } 2145 2146 /// Produce the code to do a primitive release. 2147 /// call void @objc_autoreleasePoolPop(i8* %ptr) 2148 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) { 2149 assert(value->getType() == Int8PtrTy); 2150 2151 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop; 2152 if (!fn) { 2153 std::vector<llvm::Type*> args(1, Int8PtrTy); 2154 llvm::FunctionType *fnType = 2155 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 2156 2157 // We don't want to use a weak import here; instead we should not 2158 // fall into this path. 2159 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop"); 2160 } 2161 2162 llvm::CallInst *call = Builder.CreateCall(fn, value); 2163 call->setDoesNotThrow(); 2164 } 2165 2166 /// Produce the code to do an MRR version objc_autoreleasepool_push. 2167 /// Which is: [[NSAutoreleasePool alloc] init]; 2168 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class. 2169 /// init is declared as: - (id) init; in its NSObject super class. 2170 /// 2171 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() { 2172 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 2173 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder); 2174 // [NSAutoreleasePool alloc] 2175 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc"); 2176 Selector AllocSel = getContext().Selectors.getSelector(0, &II); 2177 CallArgList Args; 2178 RValue AllocRV = 2179 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2180 getContext().getObjCIdType(), 2181 AllocSel, Receiver, Args); 2182 2183 // [Receiver init] 2184 Receiver = AllocRV.getScalarVal(); 2185 II = &CGM.getContext().Idents.get("init"); 2186 Selector InitSel = getContext().Selectors.getSelector(0, &II); 2187 RValue InitRV = 2188 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2189 getContext().getObjCIdType(), 2190 InitSel, Receiver, Args); 2191 return InitRV.getScalarVal(); 2192 } 2193 2194 /// Produce the code to do a primitive release. 2195 /// [tmp drain]; 2196 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) { 2197 IdentifierInfo *II = &CGM.getContext().Idents.get("drain"); 2198 Selector DrainSel = getContext().Selectors.getSelector(0, &II); 2199 CallArgList Args; 2200 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 2201 getContext().VoidTy, DrainSel, Arg, Args); 2202 } 2203 2204 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF, 2205 llvm::Value *addr, 2206 QualType type) { 2207 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy"); 2208 CGF.EmitARCRelease(ptr, /*precise*/ true); 2209 } 2210 2211 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF, 2212 llvm::Value *addr, 2213 QualType type) { 2214 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy"); 2215 CGF.EmitARCRelease(ptr, /*precise*/ false); 2216 } 2217 2218 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF, 2219 llvm::Value *addr, 2220 QualType type) { 2221 CGF.EmitARCDestroyWeak(addr); 2222 } 2223 2224 namespace { 2225 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup { 2226 llvm::Value *Token; 2227 2228 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 2229 2230 void Emit(CodeGenFunction &CGF, Flags flags) { 2231 CGF.EmitObjCAutoreleasePoolPop(Token); 2232 } 2233 }; 2234 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup { 2235 llvm::Value *Token; 2236 2237 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 2238 2239 void Emit(CodeGenFunction &CGF, Flags flags) { 2240 CGF.EmitObjCMRRAutoreleasePoolPop(Token); 2241 } 2242 }; 2243 } 2244 2245 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) { 2246 if (CGM.getLangOpts().ObjCAutoRefCount) 2247 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr); 2248 else 2249 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr); 2250 } 2251 2252 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2253 LValue lvalue, 2254 QualType type) { 2255 switch (type.getObjCLifetime()) { 2256 case Qualifiers::OCL_None: 2257 case Qualifiers::OCL_ExplicitNone: 2258 case Qualifiers::OCL_Strong: 2259 case Qualifiers::OCL_Autoreleasing: 2260 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(), 2261 false); 2262 2263 case Qualifiers::OCL_Weak: 2264 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()), 2265 true); 2266 } 2267 2268 llvm_unreachable("impossible lifetime!"); 2269 } 2270 2271 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2272 const Expr *e) { 2273 e = e->IgnoreParens(); 2274 QualType type = e->getType(); 2275 2276 // If we're loading retained from a __strong xvalue, we can avoid 2277 // an extra retain/release pair by zeroing out the source of this 2278 // "move" operation. 2279 if (e->isXValue() && 2280 !type.isConstQualified() && 2281 type.getObjCLifetime() == Qualifiers::OCL_Strong) { 2282 // Emit the lvalue. 2283 LValue lv = CGF.EmitLValue(e); 2284 2285 // Load the object pointer. 2286 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal(); 2287 2288 // Set the source pointer to NULL. 2289 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv); 2290 2291 return TryEmitResult(result, true); 2292 } 2293 2294 // As a very special optimization, in ARC++, if the l-value is the 2295 // result of a non-volatile assignment, do a simple retain of the 2296 // result of the call to objc_storeWeak instead of reloading. 2297 if (CGF.getLangOpts().CPlusPlus && 2298 !type.isVolatileQualified() && 2299 type.getObjCLifetime() == Qualifiers::OCL_Weak && 2300 isa<BinaryOperator>(e) && 2301 cast<BinaryOperator>(e)->getOpcode() == BO_Assign) 2302 return TryEmitResult(CGF.EmitScalarExpr(e), false); 2303 2304 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type); 2305 } 2306 2307 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 2308 llvm::Value *value); 2309 2310 /// Given that the given expression is some sort of call (which does 2311 /// not return retained), emit a retain following it. 2312 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) { 2313 llvm::Value *value = CGF.EmitScalarExpr(e); 2314 return emitARCRetainAfterCall(CGF, value); 2315 } 2316 2317 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 2318 llvm::Value *value) { 2319 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) { 2320 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 2321 2322 // Place the retain immediately following the call. 2323 CGF.Builder.SetInsertPoint(call->getParent(), 2324 ++llvm::BasicBlock::iterator(call)); 2325 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 2326 2327 CGF.Builder.restoreIP(ip); 2328 return value; 2329 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) { 2330 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 2331 2332 // Place the retain at the beginning of the normal destination block. 2333 llvm::BasicBlock *BB = invoke->getNormalDest(); 2334 CGF.Builder.SetInsertPoint(BB, BB->begin()); 2335 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 2336 2337 CGF.Builder.restoreIP(ip); 2338 return value; 2339 2340 // Bitcasts can arise because of related-result returns. Rewrite 2341 // the operand. 2342 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) { 2343 llvm::Value *operand = bitcast->getOperand(0); 2344 operand = emitARCRetainAfterCall(CGF, operand); 2345 bitcast->setOperand(0, operand); 2346 return bitcast; 2347 2348 // Generic fall-back case. 2349 } else { 2350 // Retain using the non-block variant: we never need to do a copy 2351 // of a block that's been returned to us. 2352 return CGF.EmitARCRetainNonBlock(value); 2353 } 2354 } 2355 2356 /// Determine whether it might be important to emit a separate 2357 /// objc_retain_block on the result of the given expression, or 2358 /// whether it's okay to just emit it in a +1 context. 2359 static bool shouldEmitSeparateBlockRetain(const Expr *e) { 2360 assert(e->getType()->isBlockPointerType()); 2361 e = e->IgnoreParens(); 2362 2363 // For future goodness, emit block expressions directly in +1 2364 // contexts if we can. 2365 if (isa<BlockExpr>(e)) 2366 return false; 2367 2368 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) { 2369 switch (cast->getCastKind()) { 2370 // Emitting these operations in +1 contexts is goodness. 2371 case CK_LValueToRValue: 2372 case CK_ARCReclaimReturnedObject: 2373 case CK_ARCConsumeObject: 2374 case CK_ARCProduceObject: 2375 return false; 2376 2377 // These operations preserve a block type. 2378 case CK_NoOp: 2379 case CK_BitCast: 2380 return shouldEmitSeparateBlockRetain(cast->getSubExpr()); 2381 2382 // These operations are known to be bad (or haven't been considered). 2383 case CK_AnyPointerToBlockPointerCast: 2384 default: 2385 return true; 2386 } 2387 } 2388 2389 return true; 2390 } 2391 2392 /// Try to emit a PseudoObjectExpr at +1. 2393 /// 2394 /// This massively duplicates emitPseudoObjectRValue. 2395 static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF, 2396 const PseudoObjectExpr *E) { 2397 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 2398 2399 // Find the result expression. 2400 const Expr *resultExpr = E->getResultExpr(); 2401 assert(resultExpr); 2402 TryEmitResult result; 2403 2404 for (PseudoObjectExpr::const_semantics_iterator 2405 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 2406 const Expr *semantic = *i; 2407 2408 // If this semantic expression is an opaque value, bind it 2409 // to the result of its source expression. 2410 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 2411 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 2412 OVMA opaqueData; 2413 2414 // If this semantic is the result of the pseudo-object 2415 // expression, try to evaluate the source as +1. 2416 if (ov == resultExpr) { 2417 assert(!OVMA::shouldBindAsLValue(ov)); 2418 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr()); 2419 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer())); 2420 2421 // Otherwise, just bind it. 2422 } else { 2423 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 2424 } 2425 opaques.push_back(opaqueData); 2426 2427 // Otherwise, if the expression is the result, evaluate it 2428 // and remember the result. 2429 } else if (semantic == resultExpr) { 2430 result = tryEmitARCRetainScalarExpr(CGF, semantic); 2431 2432 // Otherwise, evaluate the expression in an ignored context. 2433 } else { 2434 CGF.EmitIgnoredExpr(semantic); 2435 } 2436 } 2437 2438 // Unbind all the opaques now. 2439 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 2440 opaques[i].unbind(CGF); 2441 2442 return result; 2443 } 2444 2445 static TryEmitResult 2446 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) { 2447 // Look through cleanups. 2448 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) { 2449 CGF.enterFullExpression(cleanups); 2450 CodeGenFunction::RunCleanupsScope scope(CGF); 2451 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr()); 2452 } 2453 2454 // The desired result type, if it differs from the type of the 2455 // ultimate opaque expression. 2456 llvm::Type *resultType = 0; 2457 2458 while (true) { 2459 e = e->IgnoreParens(); 2460 2461 // There's a break at the end of this if-chain; anything 2462 // that wants to keep looping has to explicitly continue. 2463 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) { 2464 switch (ce->getCastKind()) { 2465 // No-op casts don't change the type, so we just ignore them. 2466 case CK_NoOp: 2467 e = ce->getSubExpr(); 2468 continue; 2469 2470 case CK_LValueToRValue: { 2471 TryEmitResult loadResult 2472 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr()); 2473 if (resultType) { 2474 llvm::Value *value = loadResult.getPointer(); 2475 value = CGF.Builder.CreateBitCast(value, resultType); 2476 loadResult.setPointer(value); 2477 } 2478 return loadResult; 2479 } 2480 2481 // These casts can change the type, so remember that and 2482 // soldier on. We only need to remember the outermost such 2483 // cast, though. 2484 case CK_CPointerToObjCPointerCast: 2485 case CK_BlockPointerToObjCPointerCast: 2486 case CK_AnyPointerToBlockPointerCast: 2487 case CK_BitCast: 2488 if (!resultType) 2489 resultType = CGF.ConvertType(ce->getType()); 2490 e = ce->getSubExpr(); 2491 assert(e->getType()->hasPointerRepresentation()); 2492 continue; 2493 2494 // For consumptions, just emit the subexpression and thus elide 2495 // the retain/release pair. 2496 case CK_ARCConsumeObject: { 2497 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr()); 2498 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2499 return TryEmitResult(result, true); 2500 } 2501 2502 // Block extends are net +0. Naively, we could just recurse on 2503 // the subexpression, but actually we need to ensure that the 2504 // value is copied as a block, so there's a little filter here. 2505 case CK_ARCExtendBlockObject: { 2506 llvm::Value *result; // will be a +0 value 2507 2508 // If we can't safely assume the sub-expression will produce a 2509 // block-copied value, emit the sub-expression at +0. 2510 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) { 2511 result = CGF.EmitScalarExpr(ce->getSubExpr()); 2512 2513 // Otherwise, try to emit the sub-expression at +1 recursively. 2514 } else { 2515 TryEmitResult subresult 2516 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr()); 2517 result = subresult.getPointer(); 2518 2519 // If that produced a retained value, just use that, 2520 // possibly casting down. 2521 if (subresult.getInt()) { 2522 if (resultType) 2523 result = CGF.Builder.CreateBitCast(result, resultType); 2524 return TryEmitResult(result, true); 2525 } 2526 2527 // Otherwise it's +0. 2528 } 2529 2530 // Retain the object as a block, then cast down. 2531 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true); 2532 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2533 return TryEmitResult(result, true); 2534 } 2535 2536 // For reclaims, emit the subexpression as a retained call and 2537 // skip the consumption. 2538 case CK_ARCReclaimReturnedObject: { 2539 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr()); 2540 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2541 return TryEmitResult(result, true); 2542 } 2543 2544 default: 2545 break; 2546 } 2547 2548 // Skip __extension__. 2549 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 2550 if (op->getOpcode() == UO_Extension) { 2551 e = op->getSubExpr(); 2552 continue; 2553 } 2554 2555 // For calls and message sends, use the retained-call logic. 2556 // Delegate inits are a special case in that they're the only 2557 // returns-retained expression that *isn't* surrounded by 2558 // a consume. 2559 } else if (isa<CallExpr>(e) || 2560 (isa<ObjCMessageExpr>(e) && 2561 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) { 2562 llvm::Value *result = emitARCRetainCall(CGF, e); 2563 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2564 return TryEmitResult(result, true); 2565 2566 // Look through pseudo-object expressions. 2567 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 2568 TryEmitResult result 2569 = tryEmitARCRetainPseudoObject(CGF, pseudo); 2570 if (resultType) { 2571 llvm::Value *value = result.getPointer(); 2572 value = CGF.Builder.CreateBitCast(value, resultType); 2573 result.setPointer(value); 2574 } 2575 return result; 2576 } 2577 2578 // Conservatively halt the search at any other expression kind. 2579 break; 2580 } 2581 2582 // We didn't find an obvious production, so emit what we've got and 2583 // tell the caller that we didn't manage to retain. 2584 llvm::Value *result = CGF.EmitScalarExpr(e); 2585 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2586 return TryEmitResult(result, false); 2587 } 2588 2589 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2590 LValue lvalue, 2591 QualType type) { 2592 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type); 2593 llvm::Value *value = result.getPointer(); 2594 if (!result.getInt()) 2595 value = CGF.EmitARCRetain(type, value); 2596 return value; 2597 } 2598 2599 /// EmitARCRetainScalarExpr - Semantically equivalent to 2600 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a 2601 /// best-effort attempt to peephole expressions that naturally produce 2602 /// retained objects. 2603 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) { 2604 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 2605 llvm::Value *value = result.getPointer(); 2606 if (!result.getInt()) 2607 value = EmitARCRetain(e->getType(), value); 2608 return value; 2609 } 2610 2611 llvm::Value * 2612 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) { 2613 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 2614 llvm::Value *value = result.getPointer(); 2615 if (result.getInt()) 2616 value = EmitARCAutorelease(value); 2617 else 2618 value = EmitARCRetainAutorelease(e->getType(), value); 2619 return value; 2620 } 2621 2622 llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) { 2623 llvm::Value *result; 2624 bool doRetain; 2625 2626 if (shouldEmitSeparateBlockRetain(e)) { 2627 result = EmitScalarExpr(e); 2628 doRetain = true; 2629 } else { 2630 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e); 2631 result = subresult.getPointer(); 2632 doRetain = !subresult.getInt(); 2633 } 2634 2635 if (doRetain) 2636 result = EmitARCRetainBlock(result, /*mandatory*/ true); 2637 return EmitObjCConsumeObject(e->getType(), result); 2638 } 2639 2640 llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) { 2641 // In ARC, retain and autorelease the expression. 2642 if (getLangOpts().ObjCAutoRefCount) { 2643 // Do so before running any cleanups for the full-expression. 2644 // tryEmitARCRetainScalarExpr does make an effort to do things 2645 // inside cleanups, but there are crazy cases like 2646 // @throw A().foo; 2647 // where a full retain+autorelease is required and would 2648 // otherwise happen after the destructor for the temporary. 2649 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) { 2650 enterFullExpression(ewc); 2651 expr = ewc->getSubExpr(); 2652 } 2653 2654 CodeGenFunction::RunCleanupsScope cleanups(*this); 2655 return EmitARCRetainAutoreleaseScalarExpr(expr); 2656 } 2657 2658 // Otherwise, use the normal scalar-expression emission. The 2659 // exception machinery doesn't do anything special with the 2660 // exception like retaining it, so there's no safety associated with 2661 // only running cleanups after the throw has started, and when it 2662 // matters it tends to be substantially inferior code. 2663 return EmitScalarExpr(expr); 2664 } 2665 2666 std::pair<LValue,llvm::Value*> 2667 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e, 2668 bool ignored) { 2669 // Evaluate the RHS first. 2670 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS()); 2671 llvm::Value *value = result.getPointer(); 2672 2673 bool hasImmediateRetain = result.getInt(); 2674 2675 // If we didn't emit a retained object, and the l-value is of block 2676 // type, then we need to emit the block-retain immediately in case 2677 // it invalidates the l-value. 2678 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) { 2679 value = EmitARCRetainBlock(value, /*mandatory*/ false); 2680 hasImmediateRetain = true; 2681 } 2682 2683 LValue lvalue = EmitLValue(e->getLHS()); 2684 2685 // If the RHS was emitted retained, expand this. 2686 if (hasImmediateRetain) { 2687 llvm::Value *oldValue = 2688 EmitLoadOfScalar(lvalue); 2689 EmitStoreOfScalar(value, lvalue); 2690 EmitARCRelease(oldValue, /*precise*/ false); 2691 } else { 2692 value = EmitARCStoreStrong(lvalue, value, ignored); 2693 } 2694 2695 return std::pair<LValue,llvm::Value*>(lvalue, value); 2696 } 2697 2698 std::pair<LValue,llvm::Value*> 2699 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) { 2700 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS()); 2701 LValue lvalue = EmitLValue(e->getLHS()); 2702 2703 EmitStoreOfScalar(value, lvalue); 2704 2705 return std::pair<LValue,llvm::Value*>(lvalue, value); 2706 } 2707 2708 void CodeGenFunction::EmitObjCAutoreleasePoolStmt( 2709 const ObjCAutoreleasePoolStmt &ARPS) { 2710 const Stmt *subStmt = ARPS.getSubStmt(); 2711 const CompoundStmt &S = cast<CompoundStmt>(*subStmt); 2712 2713 CGDebugInfo *DI = getDebugInfo(); 2714 if (DI) 2715 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc()); 2716 2717 // Keep track of the current cleanup stack depth. 2718 RunCleanupsScope Scope(*this); 2719 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) { 2720 llvm::Value *token = EmitObjCAutoreleasePoolPush(); 2721 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token); 2722 } else { 2723 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush(); 2724 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token); 2725 } 2726 2727 for (CompoundStmt::const_body_iterator I = S.body_begin(), 2728 E = S.body_end(); I != E; ++I) 2729 EmitStmt(*I); 2730 2731 if (DI) 2732 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc()); 2733 } 2734 2735 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 2736 /// make sure it survives garbage collection until this point. 2737 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) { 2738 // We just use an inline assembly. 2739 llvm::FunctionType *extenderType 2740 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All); 2741 llvm::Value *extender 2742 = llvm::InlineAsm::get(extenderType, 2743 /* assembly */ "", 2744 /* constraints */ "r", 2745 /* side effects */ true); 2746 2747 object = Builder.CreateBitCast(object, VoidPtrTy); 2748 Builder.CreateCall(extender, object)->setDoesNotThrow(); 2749 } 2750 2751 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with 2752 /// non-trivial copy assignment function, produce following helper function. 2753 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; } 2754 /// 2755 llvm::Constant * 2756 CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( 2757 const ObjCPropertyImplDecl *PID) { 2758 // FIXME. This api is for NeXt runtime only for now. 2759 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime) 2760 return 0; 2761 QualType Ty = PID->getPropertyIvarDecl()->getType(); 2762 if (!Ty->isRecordType()) 2763 return 0; 2764 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2765 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic))) 2766 return 0; 2767 llvm::Constant * HelperFn = 0; 2768 if (hasTrivialSetExpr(PID)) 2769 return 0; 2770 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null"); 2771 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty))) 2772 return HelperFn; 2773 2774 ASTContext &C = getContext(); 2775 IdentifierInfo *II 2776 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_"); 2777 FunctionDecl *FD = FunctionDecl::Create(C, 2778 C.getTranslationUnitDecl(), 2779 SourceLocation(), 2780 SourceLocation(), II, C.VoidTy, 0, 2781 SC_Static, 2782 SC_None, 2783 false, 2784 true); 2785 2786 QualType DestTy = C.getPointerType(Ty); 2787 QualType SrcTy = Ty; 2788 SrcTy.addConst(); 2789 SrcTy = C.getPointerType(SrcTy); 2790 2791 FunctionArgList args; 2792 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy); 2793 args.push_back(&dstDecl); 2794 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy); 2795 args.push_back(&srcDecl); 2796 2797 const CGFunctionInfo &FI = 2798 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args, 2799 FunctionType::ExtInfo(), 2800 RequiredArgs::All); 2801 2802 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); 2803 2804 llvm::Function *Fn = 2805 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 2806 "__assign_helper_atomic_property_", &CGM.getModule()); 2807 2808 if (CGM.getModuleDebugInfo()) 2809 DebugInfo = CGM.getModuleDebugInfo(); 2810 2811 2812 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 2813 2814 DeclRefExpr DstExpr(&dstDecl, false, DestTy, 2815 VK_RValue, SourceLocation()); 2816 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(), 2817 VK_LValue, OK_Ordinary, SourceLocation()); 2818 2819 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy, 2820 VK_RValue, SourceLocation()); 2821 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), 2822 VK_LValue, OK_Ordinary, SourceLocation()); 2823 2824 Expr *Args[2] = { &DST, &SRC }; 2825 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment()); 2826 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(), 2827 Args, 2, DestTy->getPointeeType(), 2828 VK_LValue, SourceLocation()); 2829 2830 EmitStmt(&TheCall); 2831 2832 FinishFunction(); 2833 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 2834 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn); 2835 return HelperFn; 2836 } 2837 2838 llvm::Constant * 2839 CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( 2840 const ObjCPropertyImplDecl *PID) { 2841 // FIXME. This api is for NeXt runtime only for now. 2842 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime) 2843 return 0; 2844 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2845 QualType Ty = PD->getType(); 2846 if (!Ty->isRecordType()) 2847 return 0; 2848 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic))) 2849 return 0; 2850 llvm::Constant * HelperFn = 0; 2851 2852 if (hasTrivialGetExpr(PID)) 2853 return 0; 2854 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null"); 2855 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty))) 2856 return HelperFn; 2857 2858 2859 ASTContext &C = getContext(); 2860 IdentifierInfo *II 2861 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_"); 2862 FunctionDecl *FD = FunctionDecl::Create(C, 2863 C.getTranslationUnitDecl(), 2864 SourceLocation(), 2865 SourceLocation(), II, C.VoidTy, 0, 2866 SC_Static, 2867 SC_None, 2868 false, 2869 true); 2870 2871 QualType DestTy = C.getPointerType(Ty); 2872 QualType SrcTy = Ty; 2873 SrcTy.addConst(); 2874 SrcTy = C.getPointerType(SrcTy); 2875 2876 FunctionArgList args; 2877 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy); 2878 args.push_back(&dstDecl); 2879 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy); 2880 args.push_back(&srcDecl); 2881 2882 const CGFunctionInfo &FI = 2883 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args, 2884 FunctionType::ExtInfo(), 2885 RequiredArgs::All); 2886 2887 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); 2888 2889 llvm::Function *Fn = 2890 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 2891 "__copy_helper_atomic_property_", &CGM.getModule()); 2892 2893 if (CGM.getModuleDebugInfo()) 2894 DebugInfo = CGM.getModuleDebugInfo(); 2895 2896 2897 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 2898 2899 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy, 2900 VK_RValue, SourceLocation()); 2901 2902 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), 2903 VK_LValue, OK_Ordinary, SourceLocation()); 2904 2905 CXXConstructExpr *CXXConstExpr = 2906 cast<CXXConstructExpr>(PID->getGetterCXXConstructor()); 2907 2908 SmallVector<Expr*, 4> ConstructorArgs; 2909 ConstructorArgs.push_back(&SRC); 2910 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin(); 2911 ++A; 2912 2913 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end(); 2914 A != AEnd; ++A) 2915 ConstructorArgs.push_back(*A); 2916 2917 CXXConstructExpr *TheCXXConstructExpr = 2918 CXXConstructExpr::Create(C, Ty, SourceLocation(), 2919 CXXConstExpr->getConstructor(), 2920 CXXConstExpr->isElidable(), 2921 &ConstructorArgs[0], ConstructorArgs.size(), 2922 CXXConstExpr->hadMultipleCandidates(), 2923 CXXConstExpr->isListInitialization(), 2924 CXXConstExpr->requiresZeroInitialization(), 2925 CXXConstExpr->getConstructionKind(), SourceRange()); 2926 2927 DeclRefExpr DstExpr(&dstDecl, false, DestTy, 2928 VK_RValue, SourceLocation()); 2929 2930 RValue DV = EmitAnyExpr(&DstExpr); 2931 CharUnits Alignment = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType()); 2932 EmitAggExpr(TheCXXConstructExpr, 2933 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(), 2934 AggValueSlot::IsDestructed, 2935 AggValueSlot::DoesNotNeedGCBarriers, 2936 AggValueSlot::IsNotAliased, 2937 AggValueSlot::IsCompleteObject)); 2938 2939 FinishFunction(); 2940 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 2941 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn); 2942 return HelperFn; 2943 } 2944 2945 llvm::Value * 2946 CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) { 2947 // Get selectors for retain/autorelease. 2948 IdentifierInfo *CopyID = &getContext().Idents.get("copy"); 2949 Selector CopySelector = 2950 getContext().Selectors.getNullarySelector(CopyID); 2951 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease"); 2952 Selector AutoreleaseSelector = 2953 getContext().Selectors.getNullarySelector(AutoreleaseID); 2954 2955 // Emit calls to retain/autorelease. 2956 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 2957 llvm::Value *Val = Block; 2958 RValue Result; 2959 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2960 Ty, CopySelector, 2961 Val, CallArgList(), 0, 0); 2962 Val = Result.getScalarVal(); 2963 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2964 Ty, AutoreleaseSelector, 2965 Val, CallArgList(), 0, 0); 2966 Val = Result.getScalarVal(); 2967 return Val; 2968 } 2969 2970 2971 CGObjCRuntime::~CGObjCRuntime() {} 2972