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