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