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