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