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