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