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