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