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