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