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