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