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