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