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