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