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