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.getLangOptions().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 (getLangOptions().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(getLangOptions().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.getLangOptions().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.getLangOptions().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.getLangOptions().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.getLangOptions().getGC() && 649 CGM.getContext().getObjCGCAttrKind(ivarType))) { 650 Kind = Expression; 651 return; 652 } 653 654 // Compute whether the ivar has strong members. 655 if (CGM.getLangOptions().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 } else { 890 llvm::Value *value; 891 if (propType->isReferenceType()) { 892 value = LV.getAddress(); 893 } else { 894 // We want to load and autoreleaseReturnValue ARC __weak ivars. 895 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 896 value = emitARCRetainLoadOfScalar(*this, LV, ivarType); 897 898 // Otherwise we want to do a simple load, suppressing the 899 // final autorelease. 900 } else { 901 value = EmitLoadOfLValue(LV).getScalarVal(); 902 AutoreleaseResult = false; 903 } 904 905 value = Builder.CreateBitCast(value, ConvertType(propType)); 906 } 907 908 EmitReturnOfRValue(RValue::get(value), propType); 909 } 910 return; 911 } 912 913 } 914 llvm_unreachable("bad @property implementation strategy!"); 915 } 916 917 /// emitStructSetterCall - Call the runtime function to store the value 918 /// from the first formal parameter into the given ivar. 919 static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD, 920 ObjCIvarDecl *ivar) { 921 // objc_copyStruct (&structIvar, &Arg, 922 // sizeof (struct something), true, false); 923 CallArgList args; 924 925 // The first argument is the address of the ivar. 926 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 927 CGF.LoadObjCSelf(), ivar, 0) 928 .getAddress(); 929 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 930 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 931 932 // The second argument is the address of the parameter variable. 933 ParmVarDecl *argVar = *OMD->param_begin(); 934 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), 935 VK_LValue, SourceLocation()); 936 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress(); 937 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); 938 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); 939 940 // The third argument is the sizeof the type. 941 llvm::Value *size = 942 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType())); 943 args.add(RValue::get(size), CGF.getContext().getSizeType()); 944 945 // The fourth argument is the 'isAtomic' flag. 946 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy); 947 948 // The fifth argument is the 'hasStrong' flag. 949 // FIXME: should this really always be false? 950 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy); 951 952 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction(); 953 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args, 954 FunctionType::ExtInfo(), 955 RequiredArgs::All), 956 copyStructFn, ReturnValueSlot(), args); 957 } 958 959 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store 960 /// the value from the first formal parameter into the given ivar, using 961 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment. 962 static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF, 963 ObjCMethodDecl *OMD, 964 ObjCIvarDecl *ivar, 965 llvm::Constant *AtomicHelperFn) { 966 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg, 967 // AtomicHelperFn); 968 CallArgList args; 969 970 // The first argument is the address of the ivar. 971 llvm::Value *ivarAddr = 972 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), 973 CGF.LoadObjCSelf(), ivar, 0).getAddress(); 974 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy); 975 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy); 976 977 // The second argument is the address of the parameter variable. 978 ParmVarDecl *argVar = *OMD->param_begin(); 979 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(), 980 VK_LValue, SourceLocation()); 981 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress(); 982 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy); 983 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy); 984 985 // Third argument is the helper function. 986 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy); 987 988 llvm::Value *copyCppAtomicObjectFn = 989 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction(); 990 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args, 991 FunctionType::ExtInfo(), 992 RequiredArgs::All), 993 copyCppAtomicObjectFn, ReturnValueSlot(), args); 994 995 996 } 997 998 999 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) { 1000 Expr *setter = PID->getSetterCXXAssignment(); 1001 if (!setter) return true; 1002 1003 // Sema only makes only of these when the ivar has a C++ class type, 1004 // so the form is pretty constrained. 1005 1006 // An operator call is trivial if the function it calls is trivial. 1007 // This also implies that there's nothing non-trivial going on with 1008 // the arguments, because operator= can only be trivial if it's a 1009 // synthesized assignment operator and therefore both parameters are 1010 // references. 1011 if (CallExpr *call = dyn_cast<CallExpr>(setter)) { 1012 if (const FunctionDecl *callee 1013 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl())) 1014 if (callee->isTrivial()) 1015 return true; 1016 return false; 1017 } 1018 1019 assert(isa<ExprWithCleanups>(setter)); 1020 return false; 1021 } 1022 1023 static bool UseOptimizedSetter(CodeGenModule &CGM) { 1024 if (CGM.getLangOptions().getGC() != LangOptions::NonGC) 1025 return false; 1026 const TargetInfo &Target = CGM.getContext().getTargetInfo(); 1027 1028 if (Target.getPlatformName() != "macosx") 1029 return false; 1030 1031 return Target.getPlatformMinVersion() >= VersionTuple(10, 8); 1032 } 1033 1034 void 1035 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1036 const ObjCPropertyImplDecl *propImpl, 1037 llvm::Constant *AtomicHelperFn) { 1038 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl(); 1039 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl(); 1040 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl(); 1041 1042 // Just use the setter expression if Sema gave us one and it's 1043 // non-trivial. 1044 if (!hasTrivialSetExpr(propImpl)) { 1045 if (!AtomicHelperFn) 1046 // If non-atomic, assignment is called directly. 1047 EmitStmt(propImpl->getSetterCXXAssignment()); 1048 else 1049 // If atomic, assignment is called via a locking api. 1050 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar, 1051 AtomicHelperFn); 1052 return; 1053 } 1054 1055 PropertyImplStrategy strategy(CGM, propImpl); 1056 switch (strategy.getKind()) { 1057 case PropertyImplStrategy::Native: { 1058 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()]; 1059 1060 LValue ivarLValue = 1061 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0); 1062 llvm::Value *ivarAddr = ivarLValue.getAddress(); 1063 1064 // Currently, all atomic accesses have to be through integer 1065 // types, so there's no point in trying to pick a prettier type. 1066 llvm::Type *bitcastType = 1067 llvm::Type::getIntNTy(getLLVMContext(), 1068 getContext().toBits(strategy.getIvarSize())); 1069 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay 1070 1071 // Cast both arguments to the chosen operation type. 1072 argAddr = Builder.CreateBitCast(argAddr, bitcastType); 1073 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType); 1074 1075 // This bitcast load is likely to cause some nasty IR. 1076 llvm::Value *load = Builder.CreateLoad(argAddr); 1077 1078 // Perform an atomic store. There are no memory ordering requirements. 1079 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr); 1080 store->setAlignment(strategy.getIvarAlignment().getQuantity()); 1081 store->setAtomic(llvm::Unordered); 1082 return; 1083 } 1084 1085 case PropertyImplStrategy::GetSetProperty: 1086 case PropertyImplStrategy::SetPropertyAndExpressionGet: { 1087 1088 llvm::Value *setOptimizedPropertyFn = 0; 1089 llvm::Value *setPropertyFn = 0; 1090 if (UseOptimizedSetter(CGM)) { 1091 // 10.8 code and GC is off 1092 setOptimizedPropertyFn = 1093 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(strategy.isAtomic(), 1094 strategy.isCopy()); 1095 if (!setOptimizedPropertyFn) { 1096 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI"); 1097 return; 1098 } 1099 } 1100 else { 1101 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction(); 1102 if (!setPropertyFn) { 1103 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy"); 1104 return; 1105 } 1106 } 1107 1108 // Emit objc_setProperty((id) self, _cmd, offset, arg, 1109 // <is-atomic>, <is-copy>). 1110 llvm::Value *cmd = 1111 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]); 1112 llvm::Value *self = 1113 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy); 1114 llvm::Value *ivarOffset = 1115 EmitIvarOffset(classImpl->getClassInterface(), ivar); 1116 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()]; 1117 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy); 1118 1119 CallArgList args; 1120 args.add(RValue::get(self), getContext().getObjCIdType()); 1121 args.add(RValue::get(cmd), getContext().getObjCSelType()); 1122 if (setOptimizedPropertyFn) { 1123 args.add(RValue::get(arg), getContext().getObjCIdType()); 1124 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 1125 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args, 1126 FunctionType::ExtInfo(), 1127 RequiredArgs::All), 1128 setOptimizedPropertyFn, ReturnValueSlot(), args); 1129 } else { 1130 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType()); 1131 args.add(RValue::get(arg), getContext().getObjCIdType()); 1132 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())), 1133 getContext().BoolTy); 1134 args.add(RValue::get(Builder.getInt1(strategy.isCopy())), 1135 getContext().BoolTy); 1136 // FIXME: We shouldn't need to get the function info here, the runtime 1137 // already should have computed it to build the function. 1138 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args, 1139 FunctionType::ExtInfo(), 1140 RequiredArgs::All), 1141 setPropertyFn, ReturnValueSlot(), args); 1142 } 1143 1144 return; 1145 } 1146 1147 case PropertyImplStrategy::CopyStruct: 1148 emitStructSetterCall(*this, setterMethod, ivar); 1149 return; 1150 1151 case PropertyImplStrategy::Expression: 1152 break; 1153 } 1154 1155 // Otherwise, fake up some ASTs and emit a normal assignment. 1156 ValueDecl *selfDecl = setterMethod->getSelfDecl(); 1157 DeclRefExpr self(selfDecl, false, selfDecl->getType(), 1158 VK_LValue, SourceLocation()); 1159 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack, 1160 selfDecl->getType(), CK_LValueToRValue, &self, 1161 VK_RValue); 1162 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(), 1163 SourceLocation(), &selfLoad, true, true); 1164 1165 ParmVarDecl *argDecl = *setterMethod->param_begin(); 1166 QualType argType = argDecl->getType().getNonReferenceType(); 1167 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation()); 1168 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack, 1169 argType.getUnqualifiedType(), CK_LValueToRValue, 1170 &arg, VK_RValue); 1171 1172 // The property type can differ from the ivar type in some situations with 1173 // Objective-C pointer types, we can always bit cast the RHS in these cases. 1174 // The following absurdity is just to ensure well-formed IR. 1175 CastKind argCK = CK_NoOp; 1176 if (ivarRef.getType()->isObjCObjectPointerType()) { 1177 if (argLoad.getType()->isObjCObjectPointerType()) 1178 argCK = CK_BitCast; 1179 else if (argLoad.getType()->isBlockPointerType()) 1180 argCK = CK_BlockPointerToObjCPointerCast; 1181 else 1182 argCK = CK_CPointerToObjCPointerCast; 1183 } else if (ivarRef.getType()->isBlockPointerType()) { 1184 if (argLoad.getType()->isBlockPointerType()) 1185 argCK = CK_BitCast; 1186 else 1187 argCK = CK_AnyPointerToBlockPointerCast; 1188 } else if (ivarRef.getType()->isPointerType()) { 1189 argCK = CK_BitCast; 1190 } 1191 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack, 1192 ivarRef.getType(), argCK, &argLoad, 1193 VK_RValue); 1194 Expr *finalArg = &argLoad; 1195 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(), 1196 argLoad.getType())) 1197 finalArg = &argCast; 1198 1199 1200 BinaryOperator assign(&ivarRef, finalArg, BO_Assign, 1201 ivarRef.getType(), VK_RValue, OK_Ordinary, 1202 SourceLocation()); 1203 EmitStmt(&assign); 1204 } 1205 1206 /// GenerateObjCSetter - Generate an Objective-C property setter 1207 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize 1208 /// is illegal within a category. 1209 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP, 1210 const ObjCPropertyImplDecl *PID) { 1211 llvm::Constant *AtomicHelperFn = 1212 GenerateObjCAtomicSetterCopyHelperFunction(PID); 1213 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1214 ObjCMethodDecl *OMD = PD->getSetterMethodDecl(); 1215 assert(OMD && "Invalid call to generate setter (empty method)"); 1216 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart()); 1217 1218 generateObjCSetterBody(IMP, PID, AtomicHelperFn); 1219 1220 FinishFunction(); 1221 } 1222 1223 namespace { 1224 struct DestroyIvar : EHScopeStack::Cleanup { 1225 private: 1226 llvm::Value *addr; 1227 const ObjCIvarDecl *ivar; 1228 CodeGenFunction::Destroyer *destroyer; 1229 bool useEHCleanupForArray; 1230 public: 1231 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar, 1232 CodeGenFunction::Destroyer *destroyer, 1233 bool useEHCleanupForArray) 1234 : addr(addr), ivar(ivar), destroyer(destroyer), 1235 useEHCleanupForArray(useEHCleanupForArray) {} 1236 1237 void Emit(CodeGenFunction &CGF, Flags flags) { 1238 LValue lvalue 1239 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0); 1240 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer, 1241 flags.isForNormalCleanup() && useEHCleanupForArray); 1242 } 1243 }; 1244 } 1245 1246 /// Like CodeGenFunction::destroyARCStrong, but do it with a call. 1247 static void destroyARCStrongWithStore(CodeGenFunction &CGF, 1248 llvm::Value *addr, 1249 QualType type) { 1250 llvm::Value *null = getNullForVariable(addr); 1251 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true); 1252 } 1253 1254 static void emitCXXDestructMethod(CodeGenFunction &CGF, 1255 ObjCImplementationDecl *impl) { 1256 CodeGenFunction::RunCleanupsScope scope(CGF); 1257 1258 llvm::Value *self = CGF.LoadObjCSelf(); 1259 1260 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 1261 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 1262 ivar; ivar = ivar->getNextIvar()) { 1263 QualType type = ivar->getType(); 1264 1265 // Check whether the ivar is a destructible type. 1266 QualType::DestructionKind dtorKind = type.isDestructedType(); 1267 if (!dtorKind) continue; 1268 1269 CodeGenFunction::Destroyer *destroyer = 0; 1270 1271 // Use a call to objc_storeStrong to destroy strong ivars, for the 1272 // general benefit of the tools. 1273 if (dtorKind == QualType::DK_objc_strong_lifetime) { 1274 destroyer = destroyARCStrongWithStore; 1275 1276 // Otherwise use the default for the destruction kind. 1277 } else { 1278 destroyer = CGF.getDestroyer(dtorKind); 1279 } 1280 1281 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind); 1282 1283 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer, 1284 cleanupKind & EHCleanup); 1285 } 1286 1287 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?"); 1288 } 1289 1290 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1291 ObjCMethodDecl *MD, 1292 bool ctor) { 1293 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface()); 1294 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart()); 1295 1296 // Emit .cxx_construct. 1297 if (ctor) { 1298 // Suppress the final autorelease in ARC. 1299 AutoreleaseResult = false; 1300 1301 SmallVector<CXXCtorInitializer *, 8> IvarInitializers; 1302 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(), 1303 E = IMP->init_end(); B != E; ++B) { 1304 CXXCtorInitializer *IvarInit = (*B); 1305 FieldDecl *Field = IvarInit->getAnyMember(); 1306 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field); 1307 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), 1308 LoadObjCSelf(), Ivar, 0); 1309 EmitAggExpr(IvarInit->getInit(), 1310 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed, 1311 AggValueSlot::DoesNotNeedGCBarriers, 1312 AggValueSlot::IsNotAliased)); 1313 } 1314 // constructor returns 'self'. 1315 CodeGenTypes &Types = CGM.getTypes(); 1316 QualType IdTy(CGM.getContext().getObjCIdType()); 1317 llvm::Value *SelfAsId = 1318 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy)); 1319 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy); 1320 1321 // Emit .cxx_destruct. 1322 } else { 1323 emitCXXDestructMethod(*this, IMP); 1324 } 1325 FinishFunction(); 1326 } 1327 1328 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) { 1329 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(); 1330 it++; it++; 1331 const ABIArgInfo &AI = it->info; 1332 // FIXME. Is this sufficient check? 1333 return (AI.getKind() == ABIArgInfo::Indirect); 1334 } 1335 1336 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) { 1337 if (CGM.getLangOptions().getGC() == LangOptions::NonGC) 1338 return false; 1339 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>()) 1340 return FDTTy->getDecl()->hasObjectMember(); 1341 return false; 1342 } 1343 1344 llvm::Value *CodeGenFunction::LoadObjCSelf() { 1345 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 1346 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self"); 1347 } 1348 1349 QualType CodeGenFunction::TypeOfSelfObject() { 1350 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl); 1351 ImplicitParamDecl *selfDecl = OMD->getSelfDecl(); 1352 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>( 1353 getContext().getCanonicalType(selfDecl->getType())); 1354 return PTy->getPointeeType(); 1355 } 1356 1357 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){ 1358 llvm::Constant *EnumerationMutationFn = 1359 CGM.getObjCRuntime().EnumerationMutationFunction(); 1360 1361 if (!EnumerationMutationFn) { 1362 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime"); 1363 return; 1364 } 1365 1366 CGDebugInfo *DI = getDebugInfo(); 1367 if (DI) 1368 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin()); 1369 1370 // The local variable comes into scope immediately. 1371 AutoVarEmission variable = AutoVarEmission::invalid(); 1372 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) 1373 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl())); 1374 1375 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end"); 1376 1377 // Fast enumeration state. 1378 QualType StateTy = CGM.getObjCFastEnumerationStateType(); 1379 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr"); 1380 EmitNullInitialization(StatePtr, StateTy); 1381 1382 // Number of elements in the items array. 1383 static const unsigned NumItems = 16; 1384 1385 // Fetch the countByEnumeratingWithState:objects:count: selector. 1386 IdentifierInfo *II[] = { 1387 &CGM.getContext().Idents.get("countByEnumeratingWithState"), 1388 &CGM.getContext().Idents.get("objects"), 1389 &CGM.getContext().Idents.get("count") 1390 }; 1391 Selector FastEnumSel = 1392 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]); 1393 1394 QualType ItemsTy = 1395 getContext().getConstantArrayType(getContext().getObjCIdType(), 1396 llvm::APInt(32, NumItems), 1397 ArrayType::Normal, 0); 1398 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr"); 1399 1400 // Emit the collection pointer. In ARC, we do a retain. 1401 llvm::Value *Collection; 1402 if (getLangOptions().ObjCAutoRefCount) { 1403 Collection = EmitARCRetainScalarExpr(S.getCollection()); 1404 1405 // Enter a cleanup to do the release. 1406 EmitObjCConsumeObject(S.getCollection()->getType(), Collection); 1407 } else { 1408 Collection = EmitScalarExpr(S.getCollection()); 1409 } 1410 1411 // The 'continue' label needs to appear within the cleanup for the 1412 // collection object. 1413 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next"); 1414 1415 // Send it our message: 1416 CallArgList Args; 1417 1418 // The first argument is a temporary of the enumeration-state type. 1419 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy)); 1420 1421 // The second argument is a temporary array with space for NumItems 1422 // pointers. We'll actually be loading elements from the array 1423 // pointer written into the control state; this buffer is so that 1424 // collections that *aren't* backed by arrays can still queue up 1425 // batches of elements. 1426 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy)); 1427 1428 // The third argument is the capacity of that temporary array. 1429 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy); 1430 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems); 1431 Args.add(RValue::get(Count), getContext().UnsignedLongTy); 1432 1433 // Start the enumeration. 1434 RValue CountRV = 1435 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 1436 getContext().UnsignedLongTy, 1437 FastEnumSel, 1438 Collection, Args); 1439 1440 // The initial number of objects that were returned in the buffer. 1441 llvm::Value *initialBufferLimit = CountRV.getScalarVal(); 1442 1443 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty"); 1444 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit"); 1445 1446 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy); 1447 1448 // If the limit pointer was zero to begin with, the collection is 1449 // empty; skip all this. 1450 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), 1451 EmptyBB, LoopInitBB); 1452 1453 // Otherwise, initialize the loop. 1454 EmitBlock(LoopInitBB); 1455 1456 // Save the initial mutations value. This is the value at an 1457 // address that was written into the state object by 1458 // countByEnumeratingWithState:objects:count:. 1459 llvm::Value *StateMutationsPtrPtr = 1460 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr"); 1461 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, 1462 "mutationsptr"); 1463 1464 llvm::Value *initialMutations = 1465 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations"); 1466 1467 // Start looping. This is the point we return to whenever we have a 1468 // fresh, non-empty batch of objects. 1469 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody"); 1470 EmitBlock(LoopBodyBB); 1471 1472 // The current index into the buffer. 1473 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index"); 1474 index->addIncoming(zero, LoopInitBB); 1475 1476 // The current buffer size. 1477 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count"); 1478 count->addIncoming(initialBufferLimit, LoopInitBB); 1479 1480 // Check whether the mutations value has changed from where it was 1481 // at start. StateMutationsPtr should actually be invariant between 1482 // refreshes. 1483 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr"); 1484 llvm::Value *currentMutations 1485 = Builder.CreateLoad(StateMutationsPtr, "statemutations"); 1486 1487 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated"); 1488 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated"); 1489 1490 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations), 1491 WasNotMutatedBB, WasMutatedBB); 1492 1493 // If so, call the enumeration-mutation function. 1494 EmitBlock(WasMutatedBB); 1495 llvm::Value *V = 1496 Builder.CreateBitCast(Collection, 1497 ConvertType(getContext().getObjCIdType())); 1498 CallArgList Args2; 1499 Args2.add(RValue::get(V), getContext().getObjCIdType()); 1500 // FIXME: We shouldn't need to get the function info here, the runtime already 1501 // should have computed it to build the function. 1502 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2, 1503 FunctionType::ExtInfo(), 1504 RequiredArgs::All), 1505 EnumerationMutationFn, ReturnValueSlot(), Args2); 1506 1507 // Otherwise, or if the mutation function returns, just continue. 1508 EmitBlock(WasNotMutatedBB); 1509 1510 // Initialize the element variable. 1511 RunCleanupsScope elementVariableScope(*this); 1512 bool elementIsVariable; 1513 LValue elementLValue; 1514 QualType elementType; 1515 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) { 1516 // Initialize the variable, in case it's a __block variable or something. 1517 EmitAutoVarInit(variable); 1518 1519 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl()); 1520 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(), 1521 VK_LValue, SourceLocation()); 1522 elementLValue = EmitLValue(&tempDRE); 1523 elementType = D->getType(); 1524 elementIsVariable = true; 1525 1526 if (D->isARCPseudoStrong()) 1527 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone); 1528 } else { 1529 elementLValue = LValue(); // suppress warning 1530 elementType = cast<Expr>(S.getElement())->getType(); 1531 elementIsVariable = false; 1532 } 1533 llvm::Type *convertedElementType = ConvertType(elementType); 1534 1535 // Fetch the buffer out of the enumeration state. 1536 // TODO: this pointer should actually be invariant between 1537 // refreshes, which would help us do certain loop optimizations. 1538 llvm::Value *StateItemsPtr = 1539 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr"); 1540 llvm::Value *EnumStateItems = 1541 Builder.CreateLoad(StateItemsPtr, "stateitems"); 1542 1543 // Fetch the value at the current index from the buffer. 1544 llvm::Value *CurrentItemPtr = 1545 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr"); 1546 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr); 1547 1548 // Cast that value to the right type. 1549 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType, 1550 "currentitem"); 1551 1552 // Make sure we have an l-value. Yes, this gets evaluated every 1553 // time through the loop. 1554 if (!elementIsVariable) { 1555 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 1556 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue); 1557 } else { 1558 EmitScalarInit(CurrentItem, elementLValue); 1559 } 1560 1561 // If we do have an element variable, this assignment is the end of 1562 // its initialization. 1563 if (elementIsVariable) 1564 EmitAutoVarCleanups(variable); 1565 1566 // Perform the loop body, setting up break and continue labels. 1567 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody)); 1568 { 1569 RunCleanupsScope Scope(*this); 1570 EmitStmt(S.getBody()); 1571 } 1572 BreakContinueStack.pop_back(); 1573 1574 // Destroy the element variable now. 1575 elementVariableScope.ForceCleanup(); 1576 1577 // Check whether there are more elements. 1578 EmitBlock(AfterBody.getBlock()); 1579 1580 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch"); 1581 1582 // First we check in the local buffer. 1583 llvm::Value *indexPlusOne 1584 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1)); 1585 1586 // If we haven't overrun the buffer yet, we can continue. 1587 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count), 1588 LoopBodyBB, FetchMoreBB); 1589 1590 index->addIncoming(indexPlusOne, AfterBody.getBlock()); 1591 count->addIncoming(count, AfterBody.getBlock()); 1592 1593 // Otherwise, we have to fetch more elements. 1594 EmitBlock(FetchMoreBB); 1595 1596 CountRV = 1597 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 1598 getContext().UnsignedLongTy, 1599 FastEnumSel, 1600 Collection, Args); 1601 1602 // If we got a zero count, we're done. 1603 llvm::Value *refetchCount = CountRV.getScalarVal(); 1604 1605 // (note that the message send might split FetchMoreBB) 1606 index->addIncoming(zero, Builder.GetInsertBlock()); 1607 count->addIncoming(refetchCount, Builder.GetInsertBlock()); 1608 1609 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero), 1610 EmptyBB, LoopBodyBB); 1611 1612 // No more elements. 1613 EmitBlock(EmptyBB); 1614 1615 if (!elementIsVariable) { 1616 // If the element was not a declaration, set it to be null. 1617 1618 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType); 1619 elementLValue = EmitLValue(cast<Expr>(S.getElement())); 1620 EmitStoreThroughLValue(RValue::get(null), elementLValue); 1621 } 1622 1623 if (DI) 1624 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd()); 1625 1626 // Leave the cleanup we entered in ARC. 1627 if (getLangOptions().ObjCAutoRefCount) 1628 PopCleanupBlock(); 1629 1630 EmitBlock(LoopEnd.getBlock()); 1631 } 1632 1633 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) { 1634 CGM.getObjCRuntime().EmitTryStmt(*this, S); 1635 } 1636 1637 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) { 1638 CGM.getObjCRuntime().EmitThrowStmt(*this, S); 1639 } 1640 1641 void CodeGenFunction::EmitObjCAtSynchronizedStmt( 1642 const ObjCAtSynchronizedStmt &S) { 1643 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S); 1644 } 1645 1646 /// Produce the code for a CK_ARCProduceObject. Just does a 1647 /// primitive retain. 1648 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type, 1649 llvm::Value *value) { 1650 return EmitARCRetain(type, value); 1651 } 1652 1653 namespace { 1654 struct CallObjCRelease : EHScopeStack::Cleanup { 1655 CallObjCRelease(llvm::Value *object) : object(object) {} 1656 llvm::Value *object; 1657 1658 void Emit(CodeGenFunction &CGF, Flags flags) { 1659 CGF.EmitARCRelease(object, /*precise*/ true); 1660 } 1661 }; 1662 } 1663 1664 /// Produce the code for a CK_ARCConsumeObject. Does a primitive 1665 /// release at the end of the full-expression. 1666 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type, 1667 llvm::Value *object) { 1668 // If we're in a conditional branch, we need to make the cleanup 1669 // conditional. 1670 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object); 1671 return object; 1672 } 1673 1674 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type, 1675 llvm::Value *value) { 1676 return EmitARCRetainAutorelease(type, value); 1677 } 1678 1679 1680 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM, 1681 llvm::FunctionType *type, 1682 StringRef fnName) { 1683 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName); 1684 1685 // In -fobjc-no-arc-runtime, emit weak references to the runtime 1686 // support library. 1687 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC) 1688 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) 1689 f->setLinkage(llvm::Function::ExternalWeakLinkage); 1690 1691 return fn; 1692 } 1693 1694 /// Perform an operation having the signature 1695 /// i8* (i8*) 1696 /// where a null input causes a no-op and returns null. 1697 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF, 1698 llvm::Value *value, 1699 llvm::Constant *&fn, 1700 StringRef fnName) { 1701 if (isa<llvm::ConstantPointerNull>(value)) return value; 1702 1703 if (!fn) { 1704 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy); 1705 llvm::FunctionType *fnType = 1706 llvm::FunctionType::get(CGF.Int8PtrTy, args, false); 1707 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1708 } 1709 1710 // Cast the argument to 'id'. 1711 llvm::Type *origType = value->getType(); 1712 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy); 1713 1714 // Call the function. 1715 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value); 1716 call->setDoesNotThrow(); 1717 1718 // Cast the result back to the original type. 1719 return CGF.Builder.CreateBitCast(call, origType); 1720 } 1721 1722 /// Perform an operation having the following signature: 1723 /// i8* (i8**) 1724 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, 1725 llvm::Value *addr, 1726 llvm::Constant *&fn, 1727 StringRef fnName) { 1728 if (!fn) { 1729 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy); 1730 llvm::FunctionType *fnType = 1731 llvm::FunctionType::get(CGF.Int8PtrTy, args, false); 1732 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1733 } 1734 1735 // Cast the argument to 'id*'. 1736 llvm::Type *origType = addr->getType(); 1737 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy); 1738 1739 // Call the function. 1740 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr); 1741 call->setDoesNotThrow(); 1742 1743 // Cast the result back to a dereference of the original type. 1744 llvm::Value *result = call; 1745 if (origType != CGF.Int8PtrPtrTy) 1746 result = CGF.Builder.CreateBitCast(result, 1747 cast<llvm::PointerType>(origType)->getElementType()); 1748 1749 return result; 1750 } 1751 1752 /// Perform an operation having the following signature: 1753 /// i8* (i8**, i8*) 1754 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, 1755 llvm::Value *addr, 1756 llvm::Value *value, 1757 llvm::Constant *&fn, 1758 StringRef fnName, 1759 bool ignored) { 1760 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 1761 == value->getType()); 1762 1763 if (!fn) { 1764 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy }; 1765 1766 llvm::FunctionType *fnType 1767 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false); 1768 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1769 } 1770 1771 llvm::Type *origType = value->getType(); 1772 1773 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy); 1774 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy); 1775 1776 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value); 1777 result->setDoesNotThrow(); 1778 1779 if (ignored) return 0; 1780 1781 return CGF.Builder.CreateBitCast(result, origType); 1782 } 1783 1784 /// Perform an operation having the following signature: 1785 /// void (i8**, i8**) 1786 static void emitARCCopyOperation(CodeGenFunction &CGF, 1787 llvm::Value *dst, 1788 llvm::Value *src, 1789 llvm::Constant *&fn, 1790 StringRef fnName) { 1791 assert(dst->getType() == src->getType()); 1792 1793 if (!fn) { 1794 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy); 1795 llvm::FunctionType *fnType 1796 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false); 1797 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName); 1798 } 1799 1800 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy); 1801 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy); 1802 1803 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src); 1804 result->setDoesNotThrow(); 1805 } 1806 1807 /// Produce the code to do a retain. Based on the type, calls one of: 1808 /// call i8* @objc_retain(i8* %value) 1809 /// call i8* @objc_retainBlock(i8* %value) 1810 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) { 1811 if (type->isBlockPointerType()) 1812 return EmitARCRetainBlock(value, /*mandatory*/ false); 1813 else 1814 return EmitARCRetainNonBlock(value); 1815 } 1816 1817 /// Retain the given object, with normal retain semantics. 1818 /// call i8* @objc_retain(i8* %value) 1819 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) { 1820 return emitARCValueOperation(*this, value, 1821 CGM.getARCEntrypoints().objc_retain, 1822 "objc_retain"); 1823 } 1824 1825 /// Retain the given block, with _Block_copy semantics. 1826 /// call i8* @objc_retainBlock(i8* %value) 1827 /// 1828 /// \param mandatory - If false, emit the call with metadata 1829 /// indicating that it's okay for the optimizer to eliminate this call 1830 /// if it can prove that the block never escapes except down the stack. 1831 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value, 1832 bool mandatory) { 1833 llvm::Value *result 1834 = emitARCValueOperation(*this, value, 1835 CGM.getARCEntrypoints().objc_retainBlock, 1836 "objc_retainBlock"); 1837 1838 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to 1839 // tell the optimizer that it doesn't need to do this copy if the 1840 // block doesn't escape, where being passed as an argument doesn't 1841 // count as escaping. 1842 if (!mandatory && isa<llvm::Instruction>(result)) { 1843 llvm::CallInst *call 1844 = cast<llvm::CallInst>(result->stripPointerCasts()); 1845 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock); 1846 1847 SmallVector<llvm::Value*,1> args; 1848 call->setMetadata("clang.arc.copy_on_escape", 1849 llvm::MDNode::get(Builder.getContext(), args)); 1850 } 1851 1852 return result; 1853 } 1854 1855 /// Retain the given object which is the result of a function call. 1856 /// call i8* @objc_retainAutoreleasedReturnValue(i8* %value) 1857 /// 1858 /// Yes, this function name is one character away from a different 1859 /// call with completely different semantics. 1860 llvm::Value * 1861 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) { 1862 // Fetch the void(void) inline asm which marks that we're going to 1863 // retain the autoreleased return value. 1864 llvm::InlineAsm *&marker 1865 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker; 1866 if (!marker) { 1867 StringRef assembly 1868 = CGM.getTargetCodeGenInfo() 1869 .getARCRetainAutoreleasedReturnValueMarker(); 1870 1871 // If we have an empty assembly string, there's nothing to do. 1872 if (assembly.empty()) { 1873 1874 // Otherwise, at -O0, build an inline asm that we're going to call 1875 // in a moment. 1876 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1877 llvm::FunctionType *type = 1878 llvm::FunctionType::get(VoidTy, /*variadic*/false); 1879 1880 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true); 1881 1882 // If we're at -O1 and above, we don't want to litter the code 1883 // with this marker yet, so leave a breadcrumb for the ARC 1884 // optimizer to pick up. 1885 } else { 1886 llvm::NamedMDNode *metadata = 1887 CGM.getModule().getOrInsertNamedMetadata( 1888 "clang.arc.retainAutoreleasedReturnValueMarker"); 1889 assert(metadata->getNumOperands() <= 1); 1890 if (metadata->getNumOperands() == 0) { 1891 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly); 1892 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string)); 1893 } 1894 } 1895 } 1896 1897 // Call the marker asm if we made one, which we do only at -O0. 1898 if (marker) Builder.CreateCall(marker); 1899 1900 return emitARCValueOperation(*this, value, 1901 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue, 1902 "objc_retainAutoreleasedReturnValue"); 1903 } 1904 1905 /// Release the given object. 1906 /// call void @objc_release(i8* %value) 1907 void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) { 1908 if (isa<llvm::ConstantPointerNull>(value)) return; 1909 1910 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release; 1911 if (!fn) { 1912 std::vector<llvm::Type*> args(1, Int8PtrTy); 1913 llvm::FunctionType *fnType = 1914 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 1915 fn = createARCRuntimeFunction(CGM, fnType, "objc_release"); 1916 } 1917 1918 // Cast the argument to 'id'. 1919 value = Builder.CreateBitCast(value, Int8PtrTy); 1920 1921 // Call objc_release. 1922 llvm::CallInst *call = Builder.CreateCall(fn, value); 1923 call->setDoesNotThrow(); 1924 1925 if (!precise) { 1926 SmallVector<llvm::Value*,1> args; 1927 call->setMetadata("clang.imprecise_release", 1928 llvm::MDNode::get(Builder.getContext(), args)); 1929 } 1930 } 1931 1932 /// Store into a strong object. Always calls this: 1933 /// call void @objc_storeStrong(i8** %addr, i8* %value) 1934 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr, 1935 llvm::Value *value, 1936 bool ignored) { 1937 assert(cast<llvm::PointerType>(addr->getType())->getElementType() 1938 == value->getType()); 1939 1940 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong; 1941 if (!fn) { 1942 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy }; 1943 llvm::FunctionType *fnType 1944 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false); 1945 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong"); 1946 } 1947 1948 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy); 1949 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy); 1950 1951 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow(); 1952 1953 if (ignored) return 0; 1954 return value; 1955 } 1956 1957 /// Store into a strong object. Sometimes calls this: 1958 /// call void @objc_storeStrong(i8** %addr, i8* %value) 1959 /// Other times, breaks it down into components. 1960 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst, 1961 llvm::Value *newValue, 1962 bool ignored) { 1963 QualType type = dst.getType(); 1964 bool isBlock = type->isBlockPointerType(); 1965 1966 // Use a store barrier at -O0 unless this is a block type or the 1967 // lvalue is inadequately aligned. 1968 if (shouldUseFusedARCCalls() && 1969 !isBlock && 1970 (dst.getAlignment().isZero() || 1971 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) { 1972 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored); 1973 } 1974 1975 // Otherwise, split it out. 1976 1977 // Retain the new value. 1978 newValue = EmitARCRetain(type, newValue); 1979 1980 // Read the old value. 1981 llvm::Value *oldValue = EmitLoadOfScalar(dst); 1982 1983 // Store. We do this before the release so that any deallocs won't 1984 // see the old value. 1985 EmitStoreOfScalar(newValue, dst); 1986 1987 // Finally, release the old value. 1988 EmitARCRelease(oldValue, /*precise*/ false); 1989 1990 return newValue; 1991 } 1992 1993 /// Autorelease the given object. 1994 /// call i8* @objc_autorelease(i8* %value) 1995 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) { 1996 return emitARCValueOperation(*this, value, 1997 CGM.getARCEntrypoints().objc_autorelease, 1998 "objc_autorelease"); 1999 } 2000 2001 /// Autorelease the given object. 2002 /// call i8* @objc_autoreleaseReturnValue(i8* %value) 2003 llvm::Value * 2004 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) { 2005 return emitARCValueOperation(*this, value, 2006 CGM.getARCEntrypoints().objc_autoreleaseReturnValue, 2007 "objc_autoreleaseReturnValue"); 2008 } 2009 2010 /// Do a fused retain/autorelease of the given object. 2011 /// call i8* @objc_retainAutoreleaseReturnValue(i8* %value) 2012 llvm::Value * 2013 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) { 2014 return emitARCValueOperation(*this, value, 2015 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue, 2016 "objc_retainAutoreleaseReturnValue"); 2017 } 2018 2019 /// Do a fused retain/autorelease of the given object. 2020 /// call i8* @objc_retainAutorelease(i8* %value) 2021 /// or 2022 /// %retain = call i8* @objc_retainBlock(i8* %value) 2023 /// call i8* @objc_autorelease(i8* %retain) 2024 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type, 2025 llvm::Value *value) { 2026 if (!type->isBlockPointerType()) 2027 return EmitARCRetainAutoreleaseNonBlock(value); 2028 2029 if (isa<llvm::ConstantPointerNull>(value)) return value; 2030 2031 llvm::Type *origType = value->getType(); 2032 value = Builder.CreateBitCast(value, Int8PtrTy); 2033 value = EmitARCRetainBlock(value, /*mandatory*/ true); 2034 value = EmitARCAutorelease(value); 2035 return Builder.CreateBitCast(value, origType); 2036 } 2037 2038 /// Do a fused retain/autorelease of the given object. 2039 /// call i8* @objc_retainAutorelease(i8* %value) 2040 llvm::Value * 2041 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) { 2042 return emitARCValueOperation(*this, value, 2043 CGM.getARCEntrypoints().objc_retainAutorelease, 2044 "objc_retainAutorelease"); 2045 } 2046 2047 /// i8* @objc_loadWeak(i8** %addr) 2048 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)). 2049 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) { 2050 return emitARCLoadOperation(*this, addr, 2051 CGM.getARCEntrypoints().objc_loadWeak, 2052 "objc_loadWeak"); 2053 } 2054 2055 /// i8* @objc_loadWeakRetained(i8** %addr) 2056 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) { 2057 return emitARCLoadOperation(*this, addr, 2058 CGM.getARCEntrypoints().objc_loadWeakRetained, 2059 "objc_loadWeakRetained"); 2060 } 2061 2062 /// i8* @objc_storeWeak(i8** %addr, i8* %value) 2063 /// Returns %value. 2064 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr, 2065 llvm::Value *value, 2066 bool ignored) { 2067 return emitARCStoreOperation(*this, addr, value, 2068 CGM.getARCEntrypoints().objc_storeWeak, 2069 "objc_storeWeak", ignored); 2070 } 2071 2072 /// i8* @objc_initWeak(i8** %addr, i8* %value) 2073 /// Returns %value. %addr is known to not have a current weak entry. 2074 /// Essentially equivalent to: 2075 /// *addr = nil; objc_storeWeak(addr, value); 2076 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) { 2077 // If we're initializing to null, just write null to memory; no need 2078 // to get the runtime involved. But don't do this if optimization 2079 // is enabled, because accounting for this would make the optimizer 2080 // much more complicated. 2081 if (isa<llvm::ConstantPointerNull>(value) && 2082 CGM.getCodeGenOpts().OptimizationLevel == 0) { 2083 Builder.CreateStore(value, addr); 2084 return; 2085 } 2086 2087 emitARCStoreOperation(*this, addr, value, 2088 CGM.getARCEntrypoints().objc_initWeak, 2089 "objc_initWeak", /*ignored*/ true); 2090 } 2091 2092 /// void @objc_destroyWeak(i8** %addr) 2093 /// Essentially objc_storeWeak(addr, nil). 2094 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) { 2095 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak; 2096 if (!fn) { 2097 std::vector<llvm::Type*> args(1, Int8PtrPtrTy); 2098 llvm::FunctionType *fnType = 2099 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 2100 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak"); 2101 } 2102 2103 // Cast the argument to 'id*'. 2104 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy); 2105 2106 llvm::CallInst *call = Builder.CreateCall(fn, addr); 2107 call->setDoesNotThrow(); 2108 } 2109 2110 /// void @objc_moveWeak(i8** %dest, i8** %src) 2111 /// Disregards the current value in %dest. Leaves %src pointing to nothing. 2112 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)). 2113 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) { 2114 emitARCCopyOperation(*this, dst, src, 2115 CGM.getARCEntrypoints().objc_moveWeak, 2116 "objc_moveWeak"); 2117 } 2118 2119 /// void @objc_copyWeak(i8** %dest, i8** %src) 2120 /// Disregards the current value in %dest. Essentially 2121 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src))) 2122 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) { 2123 emitARCCopyOperation(*this, dst, src, 2124 CGM.getARCEntrypoints().objc_copyWeak, 2125 "objc_copyWeak"); 2126 } 2127 2128 /// Produce the code to do a objc_autoreleasepool_push. 2129 /// call i8* @objc_autoreleasePoolPush(void) 2130 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() { 2131 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush; 2132 if (!fn) { 2133 llvm::FunctionType *fnType = 2134 llvm::FunctionType::get(Int8PtrTy, false); 2135 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush"); 2136 } 2137 2138 llvm::CallInst *call = Builder.CreateCall(fn); 2139 call->setDoesNotThrow(); 2140 2141 return call; 2142 } 2143 2144 /// Produce the code to do a primitive release. 2145 /// call void @objc_autoreleasePoolPop(i8* %ptr) 2146 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) { 2147 assert(value->getType() == Int8PtrTy); 2148 2149 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop; 2150 if (!fn) { 2151 std::vector<llvm::Type*> args(1, Int8PtrTy); 2152 llvm::FunctionType *fnType = 2153 llvm::FunctionType::get(Builder.getVoidTy(), args, false); 2154 2155 // We don't want to use a weak import here; instead we should not 2156 // fall into this path. 2157 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop"); 2158 } 2159 2160 llvm::CallInst *call = Builder.CreateCall(fn, value); 2161 call->setDoesNotThrow(); 2162 } 2163 2164 /// Produce the code to do an MRR version objc_autoreleasepool_push. 2165 /// Which is: [[NSAutoreleasePool alloc] init]; 2166 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class. 2167 /// init is declared as: - (id) init; in its NSObject super class. 2168 /// 2169 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() { 2170 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 2171 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder); 2172 // [NSAutoreleasePool alloc] 2173 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc"); 2174 Selector AllocSel = getContext().Selectors.getSelector(0, &II); 2175 CallArgList Args; 2176 RValue AllocRV = 2177 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2178 getContext().getObjCIdType(), 2179 AllocSel, Receiver, Args); 2180 2181 // [Receiver init] 2182 Receiver = AllocRV.getScalarVal(); 2183 II = &CGM.getContext().Idents.get("init"); 2184 Selector InitSel = getContext().Selectors.getSelector(0, &II); 2185 RValue InitRV = 2186 Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2187 getContext().getObjCIdType(), 2188 InitSel, Receiver, Args); 2189 return InitRV.getScalarVal(); 2190 } 2191 2192 /// Produce the code to do a primitive release. 2193 /// [tmp drain]; 2194 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) { 2195 IdentifierInfo *II = &CGM.getContext().Idents.get("drain"); 2196 Selector DrainSel = getContext().Selectors.getSelector(0, &II); 2197 CallArgList Args; 2198 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(), 2199 getContext().VoidTy, DrainSel, Arg, Args); 2200 } 2201 2202 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF, 2203 llvm::Value *addr, 2204 QualType type) { 2205 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy"); 2206 CGF.EmitARCRelease(ptr, /*precise*/ true); 2207 } 2208 2209 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF, 2210 llvm::Value *addr, 2211 QualType type) { 2212 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy"); 2213 CGF.EmitARCRelease(ptr, /*precise*/ false); 2214 } 2215 2216 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF, 2217 llvm::Value *addr, 2218 QualType type) { 2219 CGF.EmitARCDestroyWeak(addr); 2220 } 2221 2222 namespace { 2223 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup { 2224 llvm::Value *Token; 2225 2226 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 2227 2228 void Emit(CodeGenFunction &CGF, Flags flags) { 2229 CGF.EmitObjCAutoreleasePoolPop(Token); 2230 } 2231 }; 2232 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup { 2233 llvm::Value *Token; 2234 2235 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {} 2236 2237 void Emit(CodeGenFunction &CGF, Flags flags) { 2238 CGF.EmitObjCMRRAutoreleasePoolPop(Token); 2239 } 2240 }; 2241 } 2242 2243 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) { 2244 if (CGM.getLangOptions().ObjCAutoRefCount) 2245 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr); 2246 else 2247 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr); 2248 } 2249 2250 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2251 LValue lvalue, 2252 QualType type) { 2253 switch (type.getObjCLifetime()) { 2254 case Qualifiers::OCL_None: 2255 case Qualifiers::OCL_ExplicitNone: 2256 case Qualifiers::OCL_Strong: 2257 case Qualifiers::OCL_Autoreleasing: 2258 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(), 2259 false); 2260 2261 case Qualifiers::OCL_Weak: 2262 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()), 2263 true); 2264 } 2265 2266 llvm_unreachable("impossible lifetime!"); 2267 } 2268 2269 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2270 const Expr *e) { 2271 e = e->IgnoreParens(); 2272 QualType type = e->getType(); 2273 2274 // If we're loading retained from a __strong xvalue, we can avoid 2275 // an extra retain/release pair by zeroing out the source of this 2276 // "move" operation. 2277 if (e->isXValue() && 2278 !type.isConstQualified() && 2279 type.getObjCLifetime() == Qualifiers::OCL_Strong) { 2280 // Emit the lvalue. 2281 LValue lv = CGF.EmitLValue(e); 2282 2283 // Load the object pointer. 2284 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal(); 2285 2286 // Set the source pointer to NULL. 2287 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv); 2288 2289 return TryEmitResult(result, true); 2290 } 2291 2292 // As a very special optimization, in ARC++, if the l-value is the 2293 // result of a non-volatile assignment, do a simple retain of the 2294 // result of the call to objc_storeWeak instead of reloading. 2295 if (CGF.getLangOptions().CPlusPlus && 2296 !type.isVolatileQualified() && 2297 type.getObjCLifetime() == Qualifiers::OCL_Weak && 2298 isa<BinaryOperator>(e) && 2299 cast<BinaryOperator>(e)->getOpcode() == BO_Assign) 2300 return TryEmitResult(CGF.EmitScalarExpr(e), false); 2301 2302 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type); 2303 } 2304 2305 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 2306 llvm::Value *value); 2307 2308 /// Given that the given expression is some sort of call (which does 2309 /// not return retained), emit a retain following it. 2310 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) { 2311 llvm::Value *value = CGF.EmitScalarExpr(e); 2312 return emitARCRetainAfterCall(CGF, value); 2313 } 2314 2315 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF, 2316 llvm::Value *value) { 2317 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) { 2318 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 2319 2320 // Place the retain immediately following the call. 2321 CGF.Builder.SetInsertPoint(call->getParent(), 2322 ++llvm::BasicBlock::iterator(call)); 2323 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 2324 2325 CGF.Builder.restoreIP(ip); 2326 return value; 2327 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) { 2328 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP(); 2329 2330 // Place the retain at the beginning of the normal destination block. 2331 llvm::BasicBlock *BB = invoke->getNormalDest(); 2332 CGF.Builder.SetInsertPoint(BB, BB->begin()); 2333 value = CGF.EmitARCRetainAutoreleasedReturnValue(value); 2334 2335 CGF.Builder.restoreIP(ip); 2336 return value; 2337 2338 // Bitcasts can arise because of related-result returns. Rewrite 2339 // the operand. 2340 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) { 2341 llvm::Value *operand = bitcast->getOperand(0); 2342 operand = emitARCRetainAfterCall(CGF, operand); 2343 bitcast->setOperand(0, operand); 2344 return bitcast; 2345 2346 // Generic fall-back case. 2347 } else { 2348 // Retain using the non-block variant: we never need to do a copy 2349 // of a block that's been returned to us. 2350 return CGF.EmitARCRetainNonBlock(value); 2351 } 2352 } 2353 2354 /// Determine whether it might be important to emit a separate 2355 /// objc_retain_block on the result of the given expression, or 2356 /// whether it's okay to just emit it in a +1 context. 2357 static bool shouldEmitSeparateBlockRetain(const Expr *e) { 2358 assert(e->getType()->isBlockPointerType()); 2359 e = e->IgnoreParens(); 2360 2361 // For future goodness, emit block expressions directly in +1 2362 // contexts if we can. 2363 if (isa<BlockExpr>(e)) 2364 return false; 2365 2366 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) { 2367 switch (cast->getCastKind()) { 2368 // Emitting these operations in +1 contexts is goodness. 2369 case CK_LValueToRValue: 2370 case CK_ARCReclaimReturnedObject: 2371 case CK_ARCConsumeObject: 2372 case CK_ARCProduceObject: 2373 return false; 2374 2375 // These operations preserve a block type. 2376 case CK_NoOp: 2377 case CK_BitCast: 2378 return shouldEmitSeparateBlockRetain(cast->getSubExpr()); 2379 2380 // These operations are known to be bad (or haven't been considered). 2381 case CK_AnyPointerToBlockPointerCast: 2382 default: 2383 return true; 2384 } 2385 } 2386 2387 return true; 2388 } 2389 2390 /// Try to emit a PseudoObjectExpr at +1. 2391 /// 2392 /// This massively duplicates emitPseudoObjectRValue. 2393 static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF, 2394 const PseudoObjectExpr *E) { 2395 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 2396 2397 // Find the result expression. 2398 const Expr *resultExpr = E->getResultExpr(); 2399 assert(resultExpr); 2400 TryEmitResult result; 2401 2402 for (PseudoObjectExpr::const_semantics_iterator 2403 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 2404 const Expr *semantic = *i; 2405 2406 // If this semantic expression is an opaque value, bind it 2407 // to the result of its source expression. 2408 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 2409 typedef CodeGenFunction::OpaqueValueMappingData OVMA; 2410 OVMA opaqueData; 2411 2412 // If this semantic is the result of the pseudo-object 2413 // expression, try to evaluate the source as +1. 2414 if (ov == resultExpr) { 2415 assert(!OVMA::shouldBindAsLValue(ov)); 2416 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr()); 2417 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer())); 2418 2419 // Otherwise, just bind it. 2420 } else { 2421 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 2422 } 2423 opaques.push_back(opaqueData); 2424 2425 // Otherwise, if the expression is the result, evaluate it 2426 // and remember the result. 2427 } else if (semantic == resultExpr) { 2428 result = tryEmitARCRetainScalarExpr(CGF, semantic); 2429 2430 // Otherwise, evaluate the expression in an ignored context. 2431 } else { 2432 CGF.EmitIgnoredExpr(semantic); 2433 } 2434 } 2435 2436 // Unbind all the opaques now. 2437 for (unsigned i = 0, e = opaques.size(); i != e; ++i) 2438 opaques[i].unbind(CGF); 2439 2440 return result; 2441 } 2442 2443 static TryEmitResult 2444 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) { 2445 // Look through cleanups. 2446 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) { 2447 CGF.enterFullExpression(cleanups); 2448 CodeGenFunction::RunCleanupsScope scope(CGF); 2449 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr()); 2450 } 2451 2452 // The desired result type, if it differs from the type of the 2453 // ultimate opaque expression. 2454 llvm::Type *resultType = 0; 2455 2456 while (true) { 2457 e = e->IgnoreParens(); 2458 2459 // There's a break at the end of this if-chain; anything 2460 // that wants to keep looping has to explicitly continue. 2461 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) { 2462 switch (ce->getCastKind()) { 2463 // No-op casts don't change the type, so we just ignore them. 2464 case CK_NoOp: 2465 e = ce->getSubExpr(); 2466 continue; 2467 2468 case CK_LValueToRValue: { 2469 TryEmitResult loadResult 2470 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr()); 2471 if (resultType) { 2472 llvm::Value *value = loadResult.getPointer(); 2473 value = CGF.Builder.CreateBitCast(value, resultType); 2474 loadResult.setPointer(value); 2475 } 2476 return loadResult; 2477 } 2478 2479 // These casts can change the type, so remember that and 2480 // soldier on. We only need to remember the outermost such 2481 // cast, though. 2482 case CK_CPointerToObjCPointerCast: 2483 case CK_BlockPointerToObjCPointerCast: 2484 case CK_AnyPointerToBlockPointerCast: 2485 case CK_BitCast: 2486 if (!resultType) 2487 resultType = CGF.ConvertType(ce->getType()); 2488 e = ce->getSubExpr(); 2489 assert(e->getType()->hasPointerRepresentation()); 2490 continue; 2491 2492 // For consumptions, just emit the subexpression and thus elide 2493 // the retain/release pair. 2494 case CK_ARCConsumeObject: { 2495 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr()); 2496 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2497 return TryEmitResult(result, true); 2498 } 2499 2500 // Block extends are net +0. Naively, we could just recurse on 2501 // the subexpression, but actually we need to ensure that the 2502 // value is copied as a block, so there's a little filter here. 2503 case CK_ARCExtendBlockObject: { 2504 llvm::Value *result; // will be a +0 value 2505 2506 // If we can't safely assume the sub-expression will produce a 2507 // block-copied value, emit the sub-expression at +0. 2508 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) { 2509 result = CGF.EmitScalarExpr(ce->getSubExpr()); 2510 2511 // Otherwise, try to emit the sub-expression at +1 recursively. 2512 } else { 2513 TryEmitResult subresult 2514 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr()); 2515 result = subresult.getPointer(); 2516 2517 // If that produced a retained value, just use that, 2518 // possibly casting down. 2519 if (subresult.getInt()) { 2520 if (resultType) 2521 result = CGF.Builder.CreateBitCast(result, resultType); 2522 return TryEmitResult(result, true); 2523 } 2524 2525 // Otherwise it's +0. 2526 } 2527 2528 // Retain the object as a block, then cast down. 2529 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true); 2530 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2531 return TryEmitResult(result, true); 2532 } 2533 2534 // For reclaims, emit the subexpression as a retained call and 2535 // skip the consumption. 2536 case CK_ARCReclaimReturnedObject: { 2537 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr()); 2538 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2539 return TryEmitResult(result, true); 2540 } 2541 2542 default: 2543 break; 2544 } 2545 2546 // Skip __extension__. 2547 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) { 2548 if (op->getOpcode() == UO_Extension) { 2549 e = op->getSubExpr(); 2550 continue; 2551 } 2552 2553 // For calls and message sends, use the retained-call logic. 2554 // Delegate inits are a special case in that they're the only 2555 // returns-retained expression that *isn't* surrounded by 2556 // a consume. 2557 } else if (isa<CallExpr>(e) || 2558 (isa<ObjCMessageExpr>(e) && 2559 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) { 2560 llvm::Value *result = emitARCRetainCall(CGF, e); 2561 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2562 return TryEmitResult(result, true); 2563 2564 // Look through pseudo-object expressions. 2565 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 2566 TryEmitResult result 2567 = tryEmitARCRetainPseudoObject(CGF, pseudo); 2568 if (resultType) { 2569 llvm::Value *value = result.getPointer(); 2570 value = CGF.Builder.CreateBitCast(value, resultType); 2571 result.setPointer(value); 2572 } 2573 return result; 2574 } 2575 2576 // Conservatively halt the search at any other expression kind. 2577 break; 2578 } 2579 2580 // We didn't find an obvious production, so emit what we've got and 2581 // tell the caller that we didn't manage to retain. 2582 llvm::Value *result = CGF.EmitScalarExpr(e); 2583 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType); 2584 return TryEmitResult(result, false); 2585 } 2586 2587 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF, 2588 LValue lvalue, 2589 QualType type) { 2590 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type); 2591 llvm::Value *value = result.getPointer(); 2592 if (!result.getInt()) 2593 value = CGF.EmitARCRetain(type, value); 2594 return value; 2595 } 2596 2597 /// EmitARCRetainScalarExpr - Semantically equivalent to 2598 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a 2599 /// best-effort attempt to peephole expressions that naturally produce 2600 /// retained objects. 2601 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) { 2602 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 2603 llvm::Value *value = result.getPointer(); 2604 if (!result.getInt()) 2605 value = EmitARCRetain(e->getType(), value); 2606 return value; 2607 } 2608 2609 llvm::Value * 2610 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) { 2611 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e); 2612 llvm::Value *value = result.getPointer(); 2613 if (result.getInt()) 2614 value = EmitARCAutorelease(value); 2615 else 2616 value = EmitARCRetainAutorelease(e->getType(), value); 2617 return value; 2618 } 2619 2620 llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) { 2621 llvm::Value *result; 2622 bool doRetain; 2623 2624 if (shouldEmitSeparateBlockRetain(e)) { 2625 result = EmitScalarExpr(e); 2626 doRetain = true; 2627 } else { 2628 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e); 2629 result = subresult.getPointer(); 2630 doRetain = !subresult.getInt(); 2631 } 2632 2633 if (doRetain) 2634 result = EmitARCRetainBlock(result, /*mandatory*/ true); 2635 return EmitObjCConsumeObject(e->getType(), result); 2636 } 2637 2638 llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) { 2639 // In ARC, retain and autorelease the expression. 2640 if (getLangOptions().ObjCAutoRefCount) { 2641 // Do so before running any cleanups for the full-expression. 2642 // tryEmitARCRetainScalarExpr does make an effort to do things 2643 // inside cleanups, but there are crazy cases like 2644 // @throw A().foo; 2645 // where a full retain+autorelease is required and would 2646 // otherwise happen after the destructor for the temporary. 2647 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) { 2648 enterFullExpression(ewc); 2649 expr = ewc->getSubExpr(); 2650 } 2651 2652 CodeGenFunction::RunCleanupsScope cleanups(*this); 2653 return EmitARCRetainAutoreleaseScalarExpr(expr); 2654 } 2655 2656 // Otherwise, use the normal scalar-expression emission. The 2657 // exception machinery doesn't do anything special with the 2658 // exception like retaining it, so there's no safety associated with 2659 // only running cleanups after the throw has started, and when it 2660 // matters it tends to be substantially inferior code. 2661 return EmitScalarExpr(expr); 2662 } 2663 2664 std::pair<LValue,llvm::Value*> 2665 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e, 2666 bool ignored) { 2667 // Evaluate the RHS first. 2668 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS()); 2669 llvm::Value *value = result.getPointer(); 2670 2671 bool hasImmediateRetain = result.getInt(); 2672 2673 // If we didn't emit a retained object, and the l-value is of block 2674 // type, then we need to emit the block-retain immediately in case 2675 // it invalidates the l-value. 2676 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) { 2677 value = EmitARCRetainBlock(value, /*mandatory*/ false); 2678 hasImmediateRetain = true; 2679 } 2680 2681 LValue lvalue = EmitLValue(e->getLHS()); 2682 2683 // If the RHS was emitted retained, expand this. 2684 if (hasImmediateRetain) { 2685 llvm::Value *oldValue = 2686 EmitLoadOfScalar(lvalue); 2687 EmitStoreOfScalar(value, lvalue); 2688 EmitARCRelease(oldValue, /*precise*/ false); 2689 } else { 2690 value = EmitARCStoreStrong(lvalue, value, ignored); 2691 } 2692 2693 return std::pair<LValue,llvm::Value*>(lvalue, value); 2694 } 2695 2696 std::pair<LValue,llvm::Value*> 2697 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) { 2698 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS()); 2699 LValue lvalue = EmitLValue(e->getLHS()); 2700 2701 EmitStoreOfScalar(value, lvalue); 2702 2703 return std::pair<LValue,llvm::Value*>(lvalue, value); 2704 } 2705 2706 void CodeGenFunction::EmitObjCAutoreleasePoolStmt( 2707 const ObjCAutoreleasePoolStmt &ARPS) { 2708 const Stmt *subStmt = ARPS.getSubStmt(); 2709 const CompoundStmt &S = cast<CompoundStmt>(*subStmt); 2710 2711 CGDebugInfo *DI = getDebugInfo(); 2712 if (DI) 2713 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc()); 2714 2715 // Keep track of the current cleanup stack depth. 2716 RunCleanupsScope Scope(*this); 2717 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) { 2718 llvm::Value *token = EmitObjCAutoreleasePoolPush(); 2719 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token); 2720 } else { 2721 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush(); 2722 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token); 2723 } 2724 2725 for (CompoundStmt::const_body_iterator I = S.body_begin(), 2726 E = S.body_end(); I != E; ++I) 2727 EmitStmt(*I); 2728 2729 if (DI) 2730 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc()); 2731 } 2732 2733 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 2734 /// make sure it survives garbage collection until this point. 2735 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) { 2736 // We just use an inline assembly. 2737 llvm::FunctionType *extenderType 2738 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All); 2739 llvm::Value *extender 2740 = llvm::InlineAsm::get(extenderType, 2741 /* assembly */ "", 2742 /* constraints */ "r", 2743 /* side effects */ true); 2744 2745 object = Builder.CreateBitCast(object, VoidPtrTy); 2746 Builder.CreateCall(extender, object)->setDoesNotThrow(); 2747 } 2748 2749 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with 2750 /// non-trivial copy assignment function, produce following helper function. 2751 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; } 2752 /// 2753 llvm::Constant * 2754 CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction( 2755 const ObjCPropertyImplDecl *PID) { 2756 // FIXME. This api is for NeXt runtime only for now. 2757 if (!getLangOptions().CPlusPlus || !getLangOptions().NeXTRuntime) 2758 return 0; 2759 QualType Ty = PID->getPropertyIvarDecl()->getType(); 2760 if (!Ty->isRecordType()) 2761 return 0; 2762 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2763 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic))) 2764 return 0; 2765 llvm::Constant * HelperFn = 0; 2766 if (hasTrivialSetExpr(PID)) 2767 return 0; 2768 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null"); 2769 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty))) 2770 return HelperFn; 2771 2772 ASTContext &C = getContext(); 2773 IdentifierInfo *II 2774 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_"); 2775 FunctionDecl *FD = FunctionDecl::Create(C, 2776 C.getTranslationUnitDecl(), 2777 SourceLocation(), 2778 SourceLocation(), II, C.VoidTy, 0, 2779 SC_Static, 2780 SC_None, 2781 false, 2782 true); 2783 2784 QualType DestTy = C.getPointerType(Ty); 2785 QualType SrcTy = Ty; 2786 SrcTy.addConst(); 2787 SrcTy = C.getPointerType(SrcTy); 2788 2789 FunctionArgList args; 2790 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy); 2791 args.push_back(&dstDecl); 2792 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy); 2793 args.push_back(&srcDecl); 2794 2795 const CGFunctionInfo &FI = 2796 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args, 2797 FunctionType::ExtInfo(), 2798 RequiredArgs::All); 2799 2800 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); 2801 2802 llvm::Function *Fn = 2803 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 2804 "__assign_helper_atomic_property_", &CGM.getModule()); 2805 2806 if (CGM.getModuleDebugInfo()) 2807 DebugInfo = CGM.getModuleDebugInfo(); 2808 2809 2810 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 2811 2812 DeclRefExpr DstExpr(&dstDecl, false, DestTy, 2813 VK_RValue, SourceLocation()); 2814 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(), 2815 VK_LValue, OK_Ordinary, SourceLocation()); 2816 2817 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy, 2818 VK_RValue, SourceLocation()); 2819 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), 2820 VK_LValue, OK_Ordinary, SourceLocation()); 2821 2822 Expr *Args[2] = { &DST, &SRC }; 2823 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment()); 2824 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(), 2825 Args, 2, DestTy->getPointeeType(), 2826 VK_LValue, SourceLocation()); 2827 2828 EmitStmt(&TheCall); 2829 2830 FinishFunction(); 2831 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 2832 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn); 2833 return HelperFn; 2834 } 2835 2836 llvm::Constant * 2837 CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction( 2838 const ObjCPropertyImplDecl *PID) { 2839 // FIXME. This api is for NeXt runtime only for now. 2840 if (!getLangOptions().CPlusPlus || !getLangOptions().NeXTRuntime) 2841 return 0; 2842 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 2843 QualType Ty = PD->getType(); 2844 if (!Ty->isRecordType()) 2845 return 0; 2846 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic))) 2847 return 0; 2848 llvm::Constant * HelperFn = 0; 2849 2850 if (hasTrivialGetExpr(PID)) 2851 return 0; 2852 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null"); 2853 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty))) 2854 return HelperFn; 2855 2856 2857 ASTContext &C = getContext(); 2858 IdentifierInfo *II 2859 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_"); 2860 FunctionDecl *FD = FunctionDecl::Create(C, 2861 C.getTranslationUnitDecl(), 2862 SourceLocation(), 2863 SourceLocation(), II, C.VoidTy, 0, 2864 SC_Static, 2865 SC_None, 2866 false, 2867 true); 2868 2869 QualType DestTy = C.getPointerType(Ty); 2870 QualType SrcTy = Ty; 2871 SrcTy.addConst(); 2872 SrcTy = C.getPointerType(SrcTy); 2873 2874 FunctionArgList args; 2875 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy); 2876 args.push_back(&dstDecl); 2877 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy); 2878 args.push_back(&srcDecl); 2879 2880 const CGFunctionInfo &FI = 2881 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args, 2882 FunctionType::ExtInfo(), 2883 RequiredArgs::All); 2884 2885 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI); 2886 2887 llvm::Function *Fn = 2888 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 2889 "__copy_helper_atomic_property_", &CGM.getModule()); 2890 2891 if (CGM.getModuleDebugInfo()) 2892 DebugInfo = CGM.getModuleDebugInfo(); 2893 2894 2895 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation()); 2896 2897 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy, 2898 VK_RValue, SourceLocation()); 2899 2900 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(), 2901 VK_LValue, OK_Ordinary, SourceLocation()); 2902 2903 CXXConstructExpr *CXXConstExpr = 2904 cast<CXXConstructExpr>(PID->getGetterCXXConstructor()); 2905 2906 SmallVector<Expr*, 4> ConstructorArgs; 2907 ConstructorArgs.push_back(&SRC); 2908 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin(); 2909 ++A; 2910 2911 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end(); 2912 A != AEnd; ++A) 2913 ConstructorArgs.push_back(*A); 2914 2915 CXXConstructExpr *TheCXXConstructExpr = 2916 CXXConstructExpr::Create(C, Ty, SourceLocation(), 2917 CXXConstExpr->getConstructor(), 2918 CXXConstExpr->isElidable(), 2919 &ConstructorArgs[0], ConstructorArgs.size(), 2920 CXXConstExpr->hadMultipleCandidates(), 2921 CXXConstExpr->isListInitialization(), 2922 CXXConstExpr->requiresZeroInitialization(), 2923 CXXConstExpr->getConstructionKind(), SourceRange()); 2924 2925 DeclRefExpr DstExpr(&dstDecl, false, DestTy, 2926 VK_RValue, SourceLocation()); 2927 2928 RValue DV = EmitAnyExpr(&DstExpr); 2929 CharUnits Alignment = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType()); 2930 EmitAggExpr(TheCXXConstructExpr, 2931 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(), 2932 AggValueSlot::IsDestructed, 2933 AggValueSlot::DoesNotNeedGCBarriers, 2934 AggValueSlot::IsNotAliased)); 2935 2936 FinishFunction(); 2937 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy); 2938 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn); 2939 return HelperFn; 2940 } 2941 2942 llvm::Value * 2943 CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) { 2944 // Get selectors for retain/autorelease. 2945 IdentifierInfo *CopyID = &getContext().Idents.get("copy"); 2946 Selector CopySelector = 2947 getContext().Selectors.getNullarySelector(CopyID); 2948 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease"); 2949 Selector AutoreleaseSelector = 2950 getContext().Selectors.getNullarySelector(AutoreleaseID); 2951 2952 // Emit calls to retain/autorelease. 2953 CGObjCRuntime &Runtime = CGM.getObjCRuntime(); 2954 llvm::Value *Val = Block; 2955 RValue Result; 2956 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2957 Ty, CopySelector, 2958 Val, CallArgList(), 0, 0); 2959 Val = Result.getScalarVal(); 2960 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(), 2961 Ty, AutoreleaseSelector, 2962 Val, CallArgList(), 0, 0); 2963 Val = Result.getScalarVal(); 2964 return Val; 2965 } 2966 2967 2968 CGObjCRuntime::~CGObjCRuntime() {} 2969