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