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 "llvm/ADT/STLExtras.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/InlineAsm.h"
26 using namespace clang;
27 using namespace CodeGen;
28 
29 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30 static TryEmitResult
31 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
32 
33 /// Given the address of a variable of pointer type, find the correct
34 /// null to store into it.
35 static llvm::Constant *getNullForVariable(llvm::Value *addr) {
36   llvm::Type *type =
37     cast<llvm::PointerType>(addr->getType())->getElementType();
38   return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39 }
40 
41 /// Emits an instance of NSConstantString representing the object.
42 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
43 {
44   llvm::Constant *C =
45       CGM.getObjCRuntime().GenerateConstantString(E->getString());
46   // FIXME: This bitcast should just be made an invariant on the Runtime.
47   return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
48 }
49 
50 /// Emit a selector.
51 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
52   // Untyped selector.
53   // Note that this implementation allows for non-constant strings to be passed
54   // as arguments to @selector().  Currently, the only thing preventing this
55   // behaviour is the type checking in the front end.
56   return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
57 }
58 
59 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60   // FIXME: This should pass the Decl not the name.
61   return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
62 }
63 
64 /// \brief Adjust the type of the result of an Objective-C message send
65 /// expression when the method has a related result type.
66 static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
67                                       const Expr *E,
68                                       const ObjCMethodDecl *Method,
69                                       RValue Result) {
70   if (!Method)
71     return Result;
72 
73   if (!Method->hasRelatedResultType() ||
74       CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
75       !Result.isScalar())
76     return Result;
77 
78   // We have applied a related result type. Cast the rvalue appropriately.
79   return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80                                                CGF.ConvertType(E->getType())));
81 }
82 
83 /// Decide whether to extend the lifetime of the receiver of a
84 /// returns-inner-pointer message.
85 static bool
86 shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
87   switch (message->getReceiverKind()) {
88 
89   // For a normal instance message, we should extend unless the
90   // receiver is loaded from a variable with precise lifetime.
91   case ObjCMessageExpr::Instance: {
92     const Expr *receiver = message->getInstanceReceiver();
93     const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
94     if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
95     receiver = ice->getSubExpr()->IgnoreParens();
96 
97     // Only __strong variables.
98     if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
99       return true;
100 
101     // All ivars and fields have precise lifetime.
102     if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
103       return false;
104 
105     // Otherwise, check for variables.
106     const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
107     if (!declRef) return true;
108     const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
109     if (!var) return true;
110 
111     // All variables have precise lifetime except local variables with
112     // automatic storage duration that aren't specially marked.
113     return (var->hasLocalStorage() &&
114             !var->hasAttr<ObjCPreciseLifetimeAttr>());
115   }
116 
117   case ObjCMessageExpr::Class:
118   case ObjCMessageExpr::SuperClass:
119     // It's never necessary for class objects.
120     return false;
121 
122   case ObjCMessageExpr::SuperInstance:
123     // We generally assume that 'self' lives throughout a method call.
124     return false;
125   }
126 
127   llvm_unreachable("invalid receiver kind");
128 }
129 
130 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
131                                             ReturnValueSlot Return) {
132   // Only the lookup mechanism and first two arguments of the method
133   // implementation vary between runtimes.  We can get the receiver and
134   // arguments in generic code.
135 
136   bool isDelegateInit = E->isDelegateInitCall();
137 
138   const ObjCMethodDecl *method = E->getMethodDecl();
139 
140   // We don't retain the receiver in delegate init calls, and this is
141   // safe because the receiver value is always loaded from 'self',
142   // which we zero out.  We don't want to Block_copy block receivers,
143   // though.
144   bool retainSelf =
145     (!isDelegateInit &&
146      CGM.getLangOptions().ObjCAutoRefCount &&
147      method &&
148      method->hasAttr<NSConsumesSelfAttr>());
149 
150   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
151   bool isSuperMessage = false;
152   bool isClassMessage = false;
153   ObjCInterfaceDecl *OID = 0;
154   // Find the receiver
155   QualType ReceiverType;
156   llvm::Value *Receiver = 0;
157   switch (E->getReceiverKind()) {
158   case ObjCMessageExpr::Instance:
159     ReceiverType = E->getInstanceReceiver()->getType();
160     if (retainSelf) {
161       TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
162                                                    E->getInstanceReceiver());
163       Receiver = ter.getPointer();
164       if (ter.getInt()) retainSelf = false;
165     } else
166       Receiver = EmitScalarExpr(E->getInstanceReceiver());
167     break;
168 
169   case ObjCMessageExpr::Class: {
170     ReceiverType = E->getClassReceiver();
171     const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
172     assert(ObjTy && "Invalid Objective-C class message send");
173     OID = ObjTy->getInterface();
174     assert(OID && "Invalid Objective-C class message send");
175     Receiver = Runtime.GetClass(Builder, OID);
176     isClassMessage = true;
177     break;
178   }
179 
180   case ObjCMessageExpr::SuperInstance:
181     ReceiverType = E->getSuperType();
182     Receiver = LoadObjCSelf();
183     isSuperMessage = true;
184     break;
185 
186   case ObjCMessageExpr::SuperClass:
187     ReceiverType = E->getSuperType();
188     Receiver = LoadObjCSelf();
189     isSuperMessage = true;
190     isClassMessage = true;
191     break;
192   }
193 
194   if (retainSelf)
195     Receiver = EmitARCRetainNonBlock(Receiver);
196 
197   // In ARC, we sometimes want to "extend the lifetime"
198   // (i.e. retain+autorelease) of receivers of returns-inner-pointer
199   // messages.
200   if (getLangOptions().ObjCAutoRefCount && method &&
201       method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
202       shouldExtendReceiverForInnerPointerMessage(E))
203     Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
204 
205   QualType ResultType =
206     method ? method->getResultType() : E->getType();
207 
208   CallArgList Args;
209   EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
210 
211   // For delegate init calls in ARC, do an unsafe store of null into
212   // self.  This represents the call taking direct ownership of that
213   // value.  We have to do this after emitting the other call
214   // arguments because they might also reference self, but we don't
215   // have to worry about any of them modifying self because that would
216   // be an undefined read and write of an object in unordered
217   // expressions.
218   if (isDelegateInit) {
219     assert(getLangOptions().ObjCAutoRefCount &&
220            "delegate init calls should only be marked in ARC");
221 
222     // Do an unsafe store of null into self.
223     llvm::Value *selfAddr =
224       LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
225     assert(selfAddr && "no self entry for a delegate init call?");
226 
227     Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
228   }
229 
230   RValue result;
231   if (isSuperMessage) {
232     // super is only valid in an Objective-C method
233     const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
234     bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
235     result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
236                                               E->getSelector(),
237                                               OMD->getClassInterface(),
238                                               isCategoryImpl,
239                                               Receiver,
240                                               isClassMessage,
241                                               Args,
242                                               method);
243   } else {
244     result = Runtime.GenerateMessageSend(*this, Return, ResultType,
245                                          E->getSelector(),
246                                          Receiver, Args, OID,
247                                          method);
248   }
249 
250   // For delegate init calls in ARC, implicitly store the result of
251   // the call back into self.  This takes ownership of the value.
252   if (isDelegateInit) {
253     llvm::Value *selfAddr =
254       LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
255     llvm::Value *newSelf = result.getScalarVal();
256 
257     // The delegate return type isn't necessarily a matching type; in
258     // fact, it's quite likely to be 'id'.
259     llvm::Type *selfTy =
260       cast<llvm::PointerType>(selfAddr->getType())->getElementType();
261     newSelf = Builder.CreateBitCast(newSelf, selfTy);
262 
263     Builder.CreateStore(newSelf, selfAddr);
264   }
265 
266   return AdjustRelatedResultType(*this, E, method, result);
267 }
268 
269 namespace {
270 struct FinishARCDealloc : EHScopeStack::Cleanup {
271   void Emit(CodeGenFunction &CGF, Flags flags) {
272     const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
273 
274     const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
275     const ObjCInterfaceDecl *iface = impl->getClassInterface();
276     if (!iface->getSuperClass()) return;
277 
278     bool isCategory = isa<ObjCCategoryImplDecl>(impl);
279 
280     // Call [super dealloc] if we have a superclass.
281     llvm::Value *self = CGF.LoadObjCSelf();
282 
283     CallArgList args;
284     CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
285                                                       CGF.getContext().VoidTy,
286                                                       method->getSelector(),
287                                                       iface,
288                                                       isCategory,
289                                                       self,
290                                                       /*is class msg*/ false,
291                                                       args,
292                                                       method);
293   }
294 };
295 }
296 
297 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
298 /// the LLVM function and sets the other context used by
299 /// CodeGenFunction.
300 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
301                                       const ObjCContainerDecl *CD,
302                                       SourceLocation StartLoc) {
303   FunctionArgList args;
304   // Check if we should generate debug info for this method.
305   if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
306     DebugInfo = CGM.getModuleDebugInfo();
307 
308   llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
309 
310   const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
311   CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
312 
313   args.push_back(OMD->getSelfDecl());
314   args.push_back(OMD->getCmdDecl());
315 
316   for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
317        E = OMD->param_end(); PI != E; ++PI)
318     args.push_back(*PI);
319 
320   CurGD = OMD;
321 
322   StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
323 
324   // In ARC, certain methods get an extra cleanup.
325   if (CGM.getLangOptions().ObjCAutoRefCount &&
326       OMD->isInstanceMethod() &&
327       OMD->getSelector().isUnarySelector()) {
328     const IdentifierInfo *ident =
329       OMD->getSelector().getIdentifierInfoForSlot(0);
330     if (ident->isStr("dealloc"))
331       EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
332   }
333 }
334 
335 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
336                                               LValue lvalue, QualType type);
337 
338 /// Generate an Objective-C method.  An Objective-C method is a C function with
339 /// its pointer, name, and types registered in the class struture.
340 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
341   StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
342   EmitStmt(OMD->getBody());
343   FinishFunction(OMD->getBodyRBrace());
344 }
345 
346 /// emitStructGetterCall - Call the runtime function to load a property
347 /// into the return value slot.
348 static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
349                                  bool isAtomic, bool hasStrong) {
350   ASTContext &Context = CGF.getContext();
351 
352   llvm::Value *src =
353     CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
354                           ivar, 0).getAddress();
355 
356   // objc_copyStruct (ReturnValue, &structIvar,
357   //                  sizeof (Type of Ivar), isAtomic, false);
358   CallArgList args;
359 
360   llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
361   args.add(RValue::get(dest), Context.VoidPtrTy);
362 
363   src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
364   args.add(RValue::get(src), Context.VoidPtrTy);
365 
366   CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
367   args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
368   args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
369   args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
370 
371   llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
372   CGF.EmitCall(CGF.getTypes().getFunctionInfo(Context.VoidTy, args,
373                                               FunctionType::ExtInfo()),
374                fn, ReturnValueSlot(), args);
375 }
376 
377 /// Determine whether the given architecture supports unaligned atomic
378 /// accesses.  They don't have to be fast, just faster than a function
379 /// call and a mutex.
380 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
381   // FIXME: Allow unaligned atomic load/store on x86.  (It is not
382   // currently supported by the backend.)
383   return 0;
384 }
385 
386 /// Return the maximum size that permits atomic accesses for the given
387 /// architecture.
388 static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
389                                         llvm::Triple::ArchType arch) {
390   // ARM has 8-byte atomic accesses, but it's not clear whether we
391   // want to rely on them here.
392 
393   // In the default case, just assume that any size up to a pointer is
394   // fine given adequate alignment.
395   return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
396 }
397 
398 namespace {
399   class PropertyImplStrategy {
400   public:
401     enum StrategyKind {
402       /// The 'native' strategy is to use the architecture's provided
403       /// reads and writes.
404       Native,
405 
406       /// Use objc_setProperty and objc_getProperty.
407       GetSetProperty,
408 
409       /// Use objc_setProperty for the setter, but use expression
410       /// evaluation for the getter.
411       SetPropertyAndExpressionGet,
412 
413       /// Use objc_copyStruct.
414       CopyStruct,
415 
416       /// The 'expression' strategy is to emit normal assignment or
417       /// lvalue-to-rvalue expressions.
418       Expression
419     };
420 
421     StrategyKind getKind() const { return StrategyKind(Kind); }
422 
423     bool hasStrongMember() const { return HasStrong; }
424     bool isAtomic() const { return IsAtomic; }
425     bool isCopy() const { return IsCopy; }
426 
427     CharUnits getIvarSize() const { return IvarSize; }
428     CharUnits getIvarAlignment() const { return IvarAlignment; }
429 
430     PropertyImplStrategy(CodeGenModule &CGM,
431                          const ObjCPropertyImplDecl *propImpl);
432 
433   private:
434     unsigned Kind : 8;
435     unsigned IsAtomic : 1;
436     unsigned IsCopy : 1;
437     unsigned HasStrong : 1;
438 
439     CharUnits IvarSize;
440     CharUnits IvarAlignment;
441   };
442 }
443 
444 /// Pick an implementation strategy for the the given property synthesis.
445 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
446                                      const ObjCPropertyImplDecl *propImpl) {
447   const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
448   ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
449 
450   IsCopy = (setterKind == ObjCPropertyDecl::Copy);
451   IsAtomic = prop->isAtomic();
452   HasStrong = false; // doesn't matter here.
453 
454   // Evaluate the ivar's size and alignment.
455   ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
456   QualType ivarType = ivar->getType();
457   llvm::tie(IvarSize, IvarAlignment)
458     = CGM.getContext().getTypeInfoInChars(ivarType);
459 
460   // If we have a copy property, we always have to use getProperty/setProperty.
461   // TODO: we could actually use setProperty and an expression for non-atomics.
462   if (IsCopy) {
463     Kind = GetSetProperty;
464     return;
465   }
466 
467   // Handle retain.
468   if (setterKind == ObjCPropertyDecl::Retain) {
469     // In GC-only, there's nothing special that needs to be done.
470     if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
471       // fallthrough
472 
473     // In ARC, if the property is non-atomic, use expression emission,
474     // which translates to objc_storeStrong.  This isn't required, but
475     // it's slightly nicer.
476     } else if (CGM.getLangOptions().ObjCAutoRefCount && !IsAtomic) {
477       Kind = Expression;
478       return;
479 
480     // Otherwise, we need to at least use setProperty.  However, if
481     // the property isn't atomic, we can use normal expression
482     // emission for the getter.
483     } else if (!IsAtomic) {
484       Kind = SetPropertyAndExpressionGet;
485       return;
486 
487     // Otherwise, we have to use both setProperty and getProperty.
488     } else {
489       Kind = GetSetProperty;
490       return;
491     }
492   }
493 
494   // If we're not atomic, just use expression accesses.
495   if (!IsAtomic) {
496     Kind = Expression;
497     return;
498   }
499 
500   // Properties on bitfield ivars need to be emitted using expression
501   // accesses even if they're nominally atomic.
502   if (ivar->isBitField()) {
503     Kind = Expression;
504     return;
505   }
506 
507   // GC-qualified or ARC-qualified ivars need to be emitted as
508   // expressions.  This actually works out to being atomic anyway,
509   // except for ARC __strong, but that should trigger the above code.
510   if (ivarType.hasNonTrivialObjCLifetime() ||
511       (CGM.getLangOptions().getGC() &&
512        CGM.getContext().getObjCGCAttrKind(ivarType))) {
513     Kind = Expression;
514     return;
515   }
516 
517   // Compute whether the ivar has strong members.
518   if (CGM.getLangOptions().getGC())
519     if (const RecordType *recordType = ivarType->getAs<RecordType>())
520       HasStrong = recordType->getDecl()->hasObjectMember();
521 
522   // We can never access structs with object members with a native
523   // access, because we need to use write barriers.  This is what
524   // objc_copyStruct is for.
525   if (HasStrong) {
526     Kind = CopyStruct;
527     return;
528   }
529 
530   // Otherwise, this is target-dependent and based on the size and
531   // alignment of the ivar.
532 
533   // If the size of the ivar is not a power of two, give up.  We don't
534   // want to get into the business of doing compare-and-swaps.
535   if (!IvarSize.isPowerOfTwo()) {
536     Kind = CopyStruct;
537     return;
538   }
539 
540   llvm::Triple::ArchType arch =
541     CGM.getContext().getTargetInfo().getTriple().getArch();
542 
543   // Most architectures require memory to fit within a single cache
544   // line, so the alignment has to be at least the size of the access.
545   // Otherwise we have to grab a lock.
546   if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
547     Kind = CopyStruct;
548     return;
549   }
550 
551   // If the ivar's size exceeds the architecture's maximum atomic
552   // access size, we have to use CopyStruct.
553   if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
554     Kind = CopyStruct;
555     return;
556   }
557 
558   // Otherwise, we can use native loads and stores.
559   Kind = Native;
560 }
561 
562 /// GenerateObjCGetter - Generate an Objective-C property getter
563 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
564 /// is illegal within a category.
565 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
566                                          const ObjCPropertyImplDecl *PID) {
567   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
568   ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
569   assert(OMD && "Invalid call to generate getter (empty method)");
570   StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
571 
572   generateObjCGetterBody(IMP, PID);
573 
574   FinishFunction();
575 }
576 
577 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
578   const Expr *getter = propImpl->getGetterCXXConstructor();
579   if (!getter) return true;
580 
581   // Sema only makes only of these when the ivar has a C++ class type,
582   // so the form is pretty constrained.
583 
584   // If the property has a reference type, we might just be binding a
585   // reference, in which case the result will be a gl-value.  We should
586   // treat this as a non-trivial operation.
587   if (getter->isGLValue())
588     return false;
589 
590   // If we selected a trivial copy-constructor, we're okay.
591   if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
592     return (construct->getConstructor()->isTrivial());
593 
594   // The constructor might require cleanups (in which case it's never
595   // trivial).
596   assert(isa<ExprWithCleanups>(getter));
597   return false;
598 }
599 
600 void
601 CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
602                                         const ObjCPropertyImplDecl *propImpl) {
603   // If there's a non-trivial 'get' expression, we just have to emit that.
604   if (!hasTrivialGetExpr(propImpl)) {
605     ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
606                    /*nrvo*/ 0);
607     EmitReturnStmt(ret);
608     return;
609   }
610 
611   const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
612   QualType propType = prop->getType();
613   ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
614 
615   ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
616 
617   // Pick an implementation strategy.
618   PropertyImplStrategy strategy(CGM, propImpl);
619   switch (strategy.getKind()) {
620   case PropertyImplStrategy::Native: {
621     LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
622 
623     // Currently, all atomic accesses have to be through integer
624     // types, so there's no point in trying to pick a prettier type.
625     llvm::Type *bitcastType =
626       llvm::Type::getIntNTy(getLLVMContext(),
627                             getContext().toBits(strategy.getIvarSize()));
628     bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
629 
630     // Perform an atomic load.  This does not impose ordering constraints.
631     llvm::Value *ivarAddr = LV.getAddress();
632     ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
633     llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
634     load->setAlignment(strategy.getIvarAlignment().getQuantity());
635     load->setAtomic(llvm::Unordered);
636 
637     // Store that value into the return address.  Doing this with a
638     // bitcast is likely to produce some pretty ugly IR, but it's not
639     // the *most* terrible thing in the world.
640     Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
641 
642     // Make sure we don't do an autorelease.
643     AutoreleaseResult = false;
644     return;
645   }
646 
647   case PropertyImplStrategy::GetSetProperty: {
648     llvm::Value *getPropertyFn =
649       CGM.getObjCRuntime().GetPropertyGetFunction();
650     if (!getPropertyFn) {
651       CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
652       return;
653     }
654 
655     // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
656     // FIXME: Can't this be simpler? This might even be worse than the
657     // corresponding gcc code.
658     llvm::Value *cmd =
659       Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
660     llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
661     llvm::Value *ivarOffset =
662       EmitIvarOffset(classImpl->getClassInterface(), ivar);
663 
664     CallArgList args;
665     args.add(RValue::get(self), getContext().getObjCIdType());
666     args.add(RValue::get(cmd), getContext().getObjCSelType());
667     args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
668     args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
669              getContext().BoolTy);
670 
671     // FIXME: We shouldn't need to get the function info here, the
672     // runtime already should have computed it to build the function.
673     RValue RV = EmitCall(getTypes().getFunctionInfo(propType, args,
674                                                     FunctionType::ExtInfo()),
675                          getPropertyFn, ReturnValueSlot(), args);
676 
677     // We need to fix the type here. Ivars with copy & retain are
678     // always objects so we don't need to worry about complex or
679     // aggregates.
680     RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
681                                            getTypes().ConvertType(propType)));
682 
683     EmitReturnOfRValue(RV, propType);
684 
685     // objc_getProperty does an autorelease, so we should suppress ours.
686     AutoreleaseResult = false;
687 
688     return;
689   }
690 
691   case PropertyImplStrategy::CopyStruct:
692     emitStructGetterCall(*this, ivar, strategy.isAtomic(),
693                          strategy.hasStrongMember());
694     return;
695 
696   case PropertyImplStrategy::Expression:
697   case PropertyImplStrategy::SetPropertyAndExpressionGet: {
698     LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
699 
700     QualType ivarType = ivar->getType();
701     if (ivarType->isAnyComplexType()) {
702       ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
703                                                LV.isVolatileQualified());
704       StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
705     } else if (hasAggregateLLVMType(ivarType)) {
706       // The return value slot is guaranteed to not be aliased, but
707       // that's not necessarily the same as "on the stack", so
708       // we still potentially need objc_memmove_collectable.
709       EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
710     } else {
711       llvm::Value *value;
712       if (propType->isReferenceType()) {
713         value = LV.getAddress();
714       } else {
715         // We want to load and autoreleaseReturnValue ARC __weak ivars.
716         if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
717           value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
718 
719         // Otherwise we want to do a simple load, suppressing the
720         // final autorelease.
721         } else {
722           value = EmitLoadOfLValue(LV).getScalarVal();
723           AutoreleaseResult = false;
724         }
725 
726         value = Builder.CreateBitCast(value, ConvertType(propType));
727       }
728 
729       EmitReturnOfRValue(RValue::get(value), propType);
730     }
731     return;
732   }
733 
734   }
735   llvm_unreachable("bad @property implementation strategy!");
736 }
737 
738 /// emitStructSetterCall - Call the runtime function to store the value
739 /// from the first formal parameter into the given ivar.
740 static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
741                                  ObjCIvarDecl *ivar) {
742   // objc_copyStruct (&structIvar, &Arg,
743   //                  sizeof (struct something), true, false);
744   CallArgList args;
745 
746   // The first argument is the address of the ivar.
747   llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
748                                                 CGF.LoadObjCSelf(), ivar, 0)
749     .getAddress();
750   ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
751   args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
752 
753   // The second argument is the address of the parameter variable.
754   ParmVarDecl *argVar = *OMD->param_begin();
755   DeclRefExpr argRef(argVar, argVar->getType(), VK_LValue, SourceLocation());
756   llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
757   argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
758   args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
759 
760   // The third argument is the sizeof the type.
761   llvm::Value *size =
762     CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
763   args.add(RValue::get(size), CGF.getContext().getSizeType());
764 
765   // The fourth argument is the 'isAtomic' flag.
766   args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
767 
768   // The fifth argument is the 'hasStrong' flag.
769   // FIXME: should this really always be false?
770   args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
771 
772   llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
773   CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
774                                               FunctionType::ExtInfo()),
775                copyStructFn, ReturnValueSlot(), args);
776 }
777 
778 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
779   Expr *setter = PID->getSetterCXXAssignment();
780   if (!setter) return true;
781 
782   // Sema only makes only of these when the ivar has a C++ class type,
783   // so the form is pretty constrained.
784 
785   // An operator call is trivial if the function it calls is trivial.
786   // This also implies that there's nothing non-trivial going on with
787   // the arguments, because operator= can only be trivial if it's a
788   // synthesized assignment operator and therefore both parameters are
789   // references.
790   if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
791     if (const FunctionDecl *callee
792           = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
793       if (callee->isTrivial())
794         return true;
795     return false;
796   }
797 
798   assert(isa<ExprWithCleanups>(setter));
799   return false;
800 }
801 
802 void
803 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
804                                         const ObjCPropertyImplDecl *propImpl) {
805   // Just use the setter expression if Sema gave us one and it's
806   // non-trivial.  There's no way to do this atomically.
807   if (!hasTrivialSetExpr(propImpl)) {
808     EmitStmt(propImpl->getSetterCXXAssignment());
809     return;
810   }
811 
812   const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
813   ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
814   ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
815 
816   PropertyImplStrategy strategy(CGM, propImpl);
817   switch (strategy.getKind()) {
818   case PropertyImplStrategy::Native: {
819     llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
820 
821     LValue ivarLValue =
822       EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
823     llvm::Value *ivarAddr = ivarLValue.getAddress();
824 
825     // Currently, all atomic accesses have to be through integer
826     // types, so there's no point in trying to pick a prettier type.
827     llvm::Type *bitcastType =
828       llvm::Type::getIntNTy(getLLVMContext(),
829                             getContext().toBits(strategy.getIvarSize()));
830     bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
831 
832     // Cast both arguments to the chosen operation type.
833     argAddr = Builder.CreateBitCast(argAddr, bitcastType);
834     ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
835 
836     // This bitcast load is likely to cause some nasty IR.
837     llvm::Value *load = Builder.CreateLoad(argAddr);
838 
839     // Perform an atomic store.  There are no memory ordering requirements.
840     llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
841     store->setAlignment(strategy.getIvarAlignment().getQuantity());
842     store->setAtomic(llvm::Unordered);
843     return;
844   }
845 
846   case PropertyImplStrategy::GetSetProperty:
847   case PropertyImplStrategy::SetPropertyAndExpressionGet: {
848     llvm::Value *setPropertyFn =
849       CGM.getObjCRuntime().GetPropertySetFunction();
850     if (!setPropertyFn) {
851       CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
852       return;
853     }
854 
855     // Emit objc_setProperty((id) self, _cmd, offset, arg,
856     //                       <is-atomic>, <is-copy>).
857     llvm::Value *cmd =
858       Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
859     llvm::Value *self =
860       Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
861     llvm::Value *ivarOffset =
862       EmitIvarOffset(classImpl->getClassInterface(), ivar);
863     llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
864     arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
865 
866     CallArgList args;
867     args.add(RValue::get(self), getContext().getObjCIdType());
868     args.add(RValue::get(cmd), getContext().getObjCSelType());
869     args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
870     args.add(RValue::get(arg), getContext().getObjCIdType());
871     args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
872              getContext().BoolTy);
873     args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
874              getContext().BoolTy);
875     // FIXME: We shouldn't need to get the function info here, the runtime
876     // already should have computed it to build the function.
877     EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
878                                         FunctionType::ExtInfo()),
879              setPropertyFn, ReturnValueSlot(), args);
880     return;
881   }
882 
883   case PropertyImplStrategy::CopyStruct:
884     emitStructSetterCall(*this, setterMethod, ivar);
885     return;
886 
887   case PropertyImplStrategy::Expression:
888     break;
889   }
890 
891   // Otherwise, fake up some ASTs and emit a normal assignment.
892   ValueDecl *selfDecl = setterMethod->getSelfDecl();
893   DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
894   ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
895                             selfDecl->getType(), CK_LValueToRValue, &self,
896                             VK_RValue);
897   ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
898                           SourceLocation(), &selfLoad, true, true);
899 
900   ParmVarDecl *argDecl = *setterMethod->param_begin();
901   QualType argType = argDecl->getType().getNonReferenceType();
902   DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
903   ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
904                            argType.getUnqualifiedType(), CK_LValueToRValue,
905                            &arg, VK_RValue);
906 
907   // The property type can differ from the ivar type in some situations with
908   // Objective-C pointer types, we can always bit cast the RHS in these cases.
909   // The following absurdity is just to ensure well-formed IR.
910   CastKind argCK = CK_NoOp;
911   if (ivarRef.getType()->isObjCObjectPointerType()) {
912     if (argLoad.getType()->isObjCObjectPointerType())
913       argCK = CK_BitCast;
914     else if (argLoad.getType()->isBlockPointerType())
915       argCK = CK_BlockPointerToObjCPointerCast;
916     else
917       argCK = CK_CPointerToObjCPointerCast;
918   } else if (ivarRef.getType()->isBlockPointerType()) {
919      if (argLoad.getType()->isBlockPointerType())
920       argCK = CK_BitCast;
921     else
922       argCK = CK_AnyPointerToBlockPointerCast;
923   } else if (ivarRef.getType()->isPointerType()) {
924     argCK = CK_BitCast;
925   }
926   ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
927                            ivarRef.getType(), argCK, &argLoad,
928                            VK_RValue);
929   Expr *finalArg = &argLoad;
930   if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
931                                            argLoad.getType()))
932     finalArg = &argCast;
933 
934 
935   BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
936                         ivarRef.getType(), VK_RValue, OK_Ordinary,
937                         SourceLocation());
938   EmitStmt(&assign);
939 }
940 
941 /// GenerateObjCSetter - Generate an Objective-C property setter
942 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
943 /// is illegal within a category.
944 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
945                                          const ObjCPropertyImplDecl *PID) {
946   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
947   ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
948   assert(OMD && "Invalid call to generate setter (empty method)");
949   StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
950 
951   generateObjCSetterBody(IMP, PID);
952 
953   FinishFunction();
954 }
955 
956 namespace {
957   struct DestroyIvar : EHScopeStack::Cleanup {
958   private:
959     llvm::Value *addr;
960     const ObjCIvarDecl *ivar;
961     CodeGenFunction::Destroyer &destroyer;
962     bool useEHCleanupForArray;
963   public:
964     DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
965                 CodeGenFunction::Destroyer *destroyer,
966                 bool useEHCleanupForArray)
967       : addr(addr), ivar(ivar), destroyer(*destroyer),
968         useEHCleanupForArray(useEHCleanupForArray) {}
969 
970     void Emit(CodeGenFunction &CGF, Flags flags) {
971       LValue lvalue
972         = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
973       CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
974                       flags.isForNormalCleanup() && useEHCleanupForArray);
975     }
976   };
977 }
978 
979 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
980 static void destroyARCStrongWithStore(CodeGenFunction &CGF,
981                                       llvm::Value *addr,
982                                       QualType type) {
983   llvm::Value *null = getNullForVariable(addr);
984   CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
985 }
986 
987 static void emitCXXDestructMethod(CodeGenFunction &CGF,
988                                   ObjCImplementationDecl *impl) {
989   CodeGenFunction::RunCleanupsScope scope(CGF);
990 
991   llvm::Value *self = CGF.LoadObjCSelf();
992 
993   const ObjCInterfaceDecl *iface = impl->getClassInterface();
994   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
995        ivar; ivar = ivar->getNextIvar()) {
996     QualType type = ivar->getType();
997 
998     // Check whether the ivar is a destructible type.
999     QualType::DestructionKind dtorKind = type.isDestructedType();
1000     if (!dtorKind) continue;
1001 
1002     CodeGenFunction::Destroyer *destroyer = 0;
1003 
1004     // Use a call to objc_storeStrong to destroy strong ivars, for the
1005     // general benefit of the tools.
1006     if (dtorKind == QualType::DK_objc_strong_lifetime) {
1007       destroyer = &destroyARCStrongWithStore;
1008 
1009     // Otherwise use the default for the destruction kind.
1010     } else {
1011       destroyer = &CGF.getDestroyer(dtorKind);
1012     }
1013 
1014     CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1015 
1016     CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1017                                          cleanupKind & EHCleanup);
1018   }
1019 
1020   assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1021 }
1022 
1023 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1024                                                  ObjCMethodDecl *MD,
1025                                                  bool ctor) {
1026   MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1027   StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
1028 
1029   // Emit .cxx_construct.
1030   if (ctor) {
1031     // Suppress the final autorelease in ARC.
1032     AutoreleaseResult = false;
1033 
1034     SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
1035     for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1036            E = IMP->init_end(); B != E; ++B) {
1037       CXXCtorInitializer *IvarInit = (*B);
1038       FieldDecl *Field = IvarInit->getAnyMember();
1039       ObjCIvarDecl  *Ivar = cast<ObjCIvarDecl>(Field);
1040       LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1041                                     LoadObjCSelf(), Ivar, 0);
1042       EmitAggExpr(IvarInit->getInit(),
1043                   AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
1044                                           AggValueSlot::DoesNotNeedGCBarriers,
1045                                           AggValueSlot::IsNotAliased));
1046     }
1047     // constructor returns 'self'.
1048     CodeGenTypes &Types = CGM.getTypes();
1049     QualType IdTy(CGM.getContext().getObjCIdType());
1050     llvm::Value *SelfAsId =
1051       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1052     EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1053 
1054   // Emit .cxx_destruct.
1055   } else {
1056     emitCXXDestructMethod(*this, IMP);
1057   }
1058   FinishFunction();
1059 }
1060 
1061 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1062   CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1063   it++; it++;
1064   const ABIArgInfo &AI = it->info;
1065   // FIXME. Is this sufficient check?
1066   return (AI.getKind() == ABIArgInfo::Indirect);
1067 }
1068 
1069 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
1070   if (CGM.getLangOptions().getGC() == LangOptions::NonGC)
1071     return false;
1072   if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1073     return FDTTy->getDecl()->hasObjectMember();
1074   return false;
1075 }
1076 
1077 llvm::Value *CodeGenFunction::LoadObjCSelf() {
1078   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1079   return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
1080 }
1081 
1082 QualType CodeGenFunction::TypeOfSelfObject() {
1083   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1084   ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1085   const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1086     getContext().getCanonicalType(selfDecl->getType()));
1087   return PTy->getPointeeType();
1088 }
1089 
1090 LValue
1091 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1092   // This is a special l-value that just issues sends when we load or
1093   // store through it.
1094 
1095   // For certain base kinds, we need to emit the base immediately.
1096   llvm::Value *Base;
1097   if (E->isSuperReceiver())
1098     Base = LoadObjCSelf();
1099   else if (E->isClassReceiver())
1100     Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
1101   else
1102     Base = EmitScalarExpr(E->getBase());
1103   return LValue::MakePropertyRef(E, Base);
1104 }
1105 
1106 static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
1107                                        ReturnValueSlot Return,
1108                                        QualType ResultType,
1109                                        Selector S,
1110                                        llvm::Value *Receiver,
1111                                        const CallArgList &CallArgs) {
1112   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
1113   bool isClassMessage = OMD->isClassMethod();
1114   bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
1115   return CGF.CGM.getObjCRuntime()
1116                 .GenerateMessageSendSuper(CGF, Return, ResultType,
1117                                           S, OMD->getClassInterface(),
1118                                           isCategoryImpl, Receiver,
1119                                           isClassMessage, CallArgs);
1120 }
1121 
1122 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
1123                                                     ReturnValueSlot Return) {
1124   const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
1125   QualType ResultType = E->getGetterResultType();
1126   Selector S;
1127   const ObjCMethodDecl *method;
1128   if (E->isExplicitProperty()) {
1129     const ObjCPropertyDecl *Property = E->getExplicitProperty();
1130     S = Property->getGetterName();
1131     method = Property->getGetterMethodDecl();
1132   } else {
1133     method = E->getImplicitPropertyGetter();
1134     S = method->getSelector();
1135   }
1136 
1137   llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
1138 
1139   if (CGM.getLangOptions().ObjCAutoRefCount) {
1140     QualType receiverType;
1141     if (E->isSuperReceiver())
1142       receiverType = E->getSuperReceiverType();
1143     else if (E->isClassReceiver())
1144       receiverType = getContext().getObjCClassType();
1145     else
1146       receiverType = E->getBase()->getType();
1147   }
1148 
1149   // Accesses to 'super' follow a different code path.
1150   if (E->isSuperReceiver())
1151     return AdjustRelatedResultType(*this, E, method,
1152                                    GenerateMessageSendSuper(*this, Return,
1153                                                             ResultType,
1154                                                             S, Receiver,
1155                                                             CallArgList()));
1156   const ObjCInterfaceDecl *ReceiverClass
1157     = (E->isClassReceiver() ? E->getClassReceiver() : 0);
1158   return AdjustRelatedResultType(*this, E, method,
1159           CGM.getObjCRuntime().
1160              GenerateMessageSend(*this, Return, ResultType, S,
1161                                  Receiver, CallArgList(), ReceiverClass));
1162 }
1163 
1164 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
1165                                                         LValue Dst) {
1166   const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
1167   Selector S = E->getSetterSelector();
1168   QualType ArgType = E->getSetterArgType();
1169 
1170   // FIXME. Other than scalars, AST is not adequate for setter and
1171   // getter type mismatches which require conversion.
1172   if (Src.isScalar()) {
1173     llvm::Value *SrcVal = Src.getScalarVal();
1174     QualType DstType = getContext().getCanonicalType(ArgType);
1175     llvm::Type *DstTy = ConvertType(DstType);
1176     if (SrcVal->getType() != DstTy)
1177       Src =
1178         RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
1179   }
1180 
1181   CallArgList Args;
1182   Args.add(Src, ArgType);
1183 
1184   llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
1185   QualType ResultType = getContext().VoidTy;
1186 
1187   if (E->isSuperReceiver()) {
1188     GenerateMessageSendSuper(*this, ReturnValueSlot(),
1189                              ResultType, S, Receiver, Args);
1190     return;
1191   }
1192 
1193   const ObjCInterfaceDecl *ReceiverClass
1194     = (E->isClassReceiver() ? E->getClassReceiver() : 0);
1195 
1196   CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1197                                            ResultType, S, Receiver, Args,
1198                                            ReceiverClass);
1199 }
1200 
1201 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1202   llvm::Constant *EnumerationMutationFn =
1203     CGM.getObjCRuntime().EnumerationMutationFunction();
1204 
1205   if (!EnumerationMutationFn) {
1206     CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1207     return;
1208   }
1209 
1210   CGDebugInfo *DI = getDebugInfo();
1211   if (DI) {
1212     DI->setLocation(S.getSourceRange().getBegin());
1213     DI->EmitRegionStart(Builder);
1214   }
1215 
1216   // The local variable comes into scope immediately.
1217   AutoVarEmission variable = AutoVarEmission::invalid();
1218   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1219     variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1220 
1221   JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1222 
1223   // Fast enumeration state.
1224   QualType StateTy = CGM.getObjCFastEnumerationStateType();
1225   llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
1226   EmitNullInitialization(StatePtr, StateTy);
1227 
1228   // Number of elements in the items array.
1229   static const unsigned NumItems = 16;
1230 
1231   // Fetch the countByEnumeratingWithState:objects:count: selector.
1232   IdentifierInfo *II[] = {
1233     &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1234     &CGM.getContext().Idents.get("objects"),
1235     &CGM.getContext().Idents.get("count")
1236   };
1237   Selector FastEnumSel =
1238     CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1239 
1240   QualType ItemsTy =
1241     getContext().getConstantArrayType(getContext().getObjCIdType(),
1242                                       llvm::APInt(32, NumItems),
1243                                       ArrayType::Normal, 0);
1244   llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1245 
1246   // Emit the collection pointer.  In ARC, we do a retain.
1247   llvm::Value *Collection;
1248   if (getLangOptions().ObjCAutoRefCount) {
1249     Collection = EmitARCRetainScalarExpr(S.getCollection());
1250 
1251     // Enter a cleanup to do the release.
1252     EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1253   } else {
1254     Collection = EmitScalarExpr(S.getCollection());
1255   }
1256 
1257   // The 'continue' label needs to appear within the cleanup for the
1258   // collection object.
1259   JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1260 
1261   // Send it our message:
1262   CallArgList Args;
1263 
1264   // The first argument is a temporary of the enumeration-state type.
1265   Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
1266 
1267   // The second argument is a temporary array with space for NumItems
1268   // pointers.  We'll actually be loading elements from the array
1269   // pointer written into the control state; this buffer is so that
1270   // collections that *aren't* backed by arrays can still queue up
1271   // batches of elements.
1272   Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
1273 
1274   // The third argument is the capacity of that temporary array.
1275   llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
1276   llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
1277   Args.add(RValue::get(Count), getContext().UnsignedLongTy);
1278 
1279   // Start the enumeration.
1280   RValue CountRV =
1281     CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1282                                              getContext().UnsignedLongTy,
1283                                              FastEnumSel,
1284                                              Collection, Args);
1285 
1286   // The initial number of objects that were returned in the buffer.
1287   llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1288 
1289   llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1290   llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1291 
1292   llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
1293 
1294   // If the limit pointer was zero to begin with, the collection is
1295   // empty; skip all this.
1296   Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1297                        EmptyBB, LoopInitBB);
1298 
1299   // Otherwise, initialize the loop.
1300   EmitBlock(LoopInitBB);
1301 
1302   // Save the initial mutations value.  This is the value at an
1303   // address that was written into the state object by
1304   // countByEnumeratingWithState:objects:count:.
1305   llvm::Value *StateMutationsPtrPtr =
1306     Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1307   llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
1308                                                       "mutationsptr");
1309 
1310   llvm::Value *initialMutations =
1311     Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
1312 
1313   // Start looping.  This is the point we return to whenever we have a
1314   // fresh, non-empty batch of objects.
1315   llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1316   EmitBlock(LoopBodyBB);
1317 
1318   // The current index into the buffer.
1319   llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
1320   index->addIncoming(zero, LoopInitBB);
1321 
1322   // The current buffer size.
1323   llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
1324   count->addIncoming(initialBufferLimit, LoopInitBB);
1325 
1326   // Check whether the mutations value has changed from where it was
1327   // at start.  StateMutationsPtr should actually be invariant between
1328   // refreshes.
1329   StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1330   llvm::Value *currentMutations
1331     = Builder.CreateLoad(StateMutationsPtr, "statemutations");
1332 
1333   llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1334   llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1335 
1336   Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1337                        WasNotMutatedBB, WasMutatedBB);
1338 
1339   // If so, call the enumeration-mutation function.
1340   EmitBlock(WasMutatedBB);
1341   llvm::Value *V =
1342     Builder.CreateBitCast(Collection,
1343                           ConvertType(getContext().getObjCIdType()),
1344                           "tmp");
1345   CallArgList Args2;
1346   Args2.add(RValue::get(V), getContext().getObjCIdType());
1347   // FIXME: We shouldn't need to get the function info here, the runtime already
1348   // should have computed it to build the function.
1349   EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
1350                                           FunctionType::ExtInfo()),
1351            EnumerationMutationFn, ReturnValueSlot(), Args2);
1352 
1353   // Otherwise, or if the mutation function returns, just continue.
1354   EmitBlock(WasNotMutatedBB);
1355 
1356   // Initialize the element variable.
1357   RunCleanupsScope elementVariableScope(*this);
1358   bool elementIsVariable;
1359   LValue elementLValue;
1360   QualType elementType;
1361   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1362     // Initialize the variable, in case it's a __block variable or something.
1363     EmitAutoVarInit(variable);
1364 
1365     const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
1366     DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1367                         VK_LValue, SourceLocation());
1368     elementLValue = EmitLValue(&tempDRE);
1369     elementType = D->getType();
1370     elementIsVariable = true;
1371 
1372     if (D->isARCPseudoStrong())
1373       elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1374   } else {
1375     elementLValue = LValue(); // suppress warning
1376     elementType = cast<Expr>(S.getElement())->getType();
1377     elementIsVariable = false;
1378   }
1379   llvm::Type *convertedElementType = ConvertType(elementType);
1380 
1381   // Fetch the buffer out of the enumeration state.
1382   // TODO: this pointer should actually be invariant between
1383   // refreshes, which would help us do certain loop optimizations.
1384   llvm::Value *StateItemsPtr =
1385     Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1386   llvm::Value *EnumStateItems =
1387     Builder.CreateLoad(StateItemsPtr, "stateitems");
1388 
1389   // Fetch the value at the current index from the buffer.
1390   llvm::Value *CurrentItemPtr =
1391     Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1392   llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
1393 
1394   // Cast that value to the right type.
1395   CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1396                                       "currentitem");
1397 
1398   // Make sure we have an l-value.  Yes, this gets evaluated every
1399   // time through the loop.
1400   if (!elementIsVariable) {
1401     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1402     EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1403   } else {
1404     EmitScalarInit(CurrentItem, elementLValue);
1405   }
1406 
1407   // If we do have an element variable, this assignment is the end of
1408   // its initialization.
1409   if (elementIsVariable)
1410     EmitAutoVarCleanups(variable);
1411 
1412   // Perform the loop body, setting up break and continue labels.
1413   BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1414   {
1415     RunCleanupsScope Scope(*this);
1416     EmitStmt(S.getBody());
1417   }
1418   BreakContinueStack.pop_back();
1419 
1420   // Destroy the element variable now.
1421   elementVariableScope.ForceCleanup();
1422 
1423   // Check whether there are more elements.
1424   EmitBlock(AfterBody.getBlock());
1425 
1426   llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1427 
1428   // First we check in the local buffer.
1429   llvm::Value *indexPlusOne
1430     = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
1431 
1432   // If we haven't overrun the buffer yet, we can continue.
1433   Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1434                        LoopBodyBB, FetchMoreBB);
1435 
1436   index->addIncoming(indexPlusOne, AfterBody.getBlock());
1437   count->addIncoming(count, AfterBody.getBlock());
1438 
1439   // Otherwise, we have to fetch more elements.
1440   EmitBlock(FetchMoreBB);
1441 
1442   CountRV =
1443     CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1444                                              getContext().UnsignedLongTy,
1445                                              FastEnumSel,
1446                                              Collection, Args);
1447 
1448   // If we got a zero count, we're done.
1449   llvm::Value *refetchCount = CountRV.getScalarVal();
1450 
1451   // (note that the message send might split FetchMoreBB)
1452   index->addIncoming(zero, Builder.GetInsertBlock());
1453   count->addIncoming(refetchCount, Builder.GetInsertBlock());
1454 
1455   Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1456                        EmptyBB, LoopBodyBB);
1457 
1458   // No more elements.
1459   EmitBlock(EmptyBB);
1460 
1461   if (!elementIsVariable) {
1462     // If the element was not a declaration, set it to be null.
1463 
1464     llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1465     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1466     EmitStoreThroughLValue(RValue::get(null), elementLValue);
1467   }
1468 
1469   if (DI) {
1470     DI->setLocation(S.getSourceRange().getEnd());
1471     DI->EmitRegionEnd(Builder);
1472   }
1473 
1474   // Leave the cleanup we entered in ARC.
1475   if (getLangOptions().ObjCAutoRefCount)
1476     PopCleanupBlock();
1477 
1478   EmitBlock(LoopEnd.getBlock());
1479 }
1480 
1481 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1482   CGM.getObjCRuntime().EmitTryStmt(*this, S);
1483 }
1484 
1485 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1486   CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1487 }
1488 
1489 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1490                                               const ObjCAtSynchronizedStmt &S) {
1491   CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1492 }
1493 
1494 /// Produce the code for a CK_ARCProduceObject.  Just does a
1495 /// primitive retain.
1496 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1497                                                     llvm::Value *value) {
1498   return EmitARCRetain(type, value);
1499 }
1500 
1501 namespace {
1502   struct CallObjCRelease : EHScopeStack::Cleanup {
1503     CallObjCRelease(llvm::Value *object) : object(object) {}
1504     llvm::Value *object;
1505 
1506     void Emit(CodeGenFunction &CGF, Flags flags) {
1507       CGF.EmitARCRelease(object, /*precise*/ true);
1508     }
1509   };
1510 }
1511 
1512 /// Produce the code for a CK_ARCConsumeObject.  Does a primitive
1513 /// release at the end of the full-expression.
1514 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1515                                                     llvm::Value *object) {
1516   // If we're in a conditional branch, we need to make the cleanup
1517   // conditional.
1518   pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
1519   return object;
1520 }
1521 
1522 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1523                                                            llvm::Value *value) {
1524   return EmitARCRetainAutorelease(type, value);
1525 }
1526 
1527 
1528 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
1529                                                 llvm::FunctionType *type,
1530                                                 StringRef fnName) {
1531   llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1532 
1533   // In -fobjc-no-arc-runtime, emit weak references to the runtime
1534   // support library.
1535   if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
1536     if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1537       f->setLinkage(llvm::Function::ExternalWeakLinkage);
1538 
1539   return fn;
1540 }
1541 
1542 /// Perform an operation having the signature
1543 ///   i8* (i8*)
1544 /// where a null input causes a no-op and returns null.
1545 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1546                                           llvm::Value *value,
1547                                           llvm::Constant *&fn,
1548                                           StringRef fnName) {
1549   if (isa<llvm::ConstantPointerNull>(value)) return value;
1550 
1551   if (!fn) {
1552     std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
1553     llvm::FunctionType *fnType =
1554       llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1555     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1556   }
1557 
1558   // Cast the argument to 'id'.
1559   llvm::Type *origType = value->getType();
1560   value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1561 
1562   // Call the function.
1563   llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1564   call->setDoesNotThrow();
1565 
1566   // Cast the result back to the original type.
1567   return CGF.Builder.CreateBitCast(call, origType);
1568 }
1569 
1570 /// Perform an operation having the following signature:
1571 ///   i8* (i8**)
1572 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1573                                          llvm::Value *addr,
1574                                          llvm::Constant *&fn,
1575                                          StringRef fnName) {
1576   if (!fn) {
1577     std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
1578     llvm::FunctionType *fnType =
1579       llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1580     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1581   }
1582 
1583   // Cast the argument to 'id*'.
1584   llvm::Type *origType = addr->getType();
1585   addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1586 
1587   // Call the function.
1588   llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1589   call->setDoesNotThrow();
1590 
1591   // Cast the result back to a dereference of the original type.
1592   llvm::Value *result = call;
1593   if (origType != CGF.Int8PtrPtrTy)
1594     result = CGF.Builder.CreateBitCast(result,
1595                         cast<llvm::PointerType>(origType)->getElementType());
1596 
1597   return result;
1598 }
1599 
1600 /// Perform an operation having the following signature:
1601 ///   i8* (i8**, i8*)
1602 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1603                                           llvm::Value *addr,
1604                                           llvm::Value *value,
1605                                           llvm::Constant *&fn,
1606                                           StringRef fnName,
1607                                           bool ignored) {
1608   assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1609            == value->getType());
1610 
1611   if (!fn) {
1612     std::vector<llvm::Type*> argTypes(2);
1613     argTypes[0] = CGF.Int8PtrPtrTy;
1614     argTypes[1] = CGF.Int8PtrTy;
1615 
1616     llvm::FunctionType *fnType
1617       = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1618     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1619   }
1620 
1621   llvm::Type *origType = value->getType();
1622 
1623   addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1624   value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1625 
1626   llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1627   result->setDoesNotThrow();
1628 
1629   if (ignored) return 0;
1630 
1631   return CGF.Builder.CreateBitCast(result, origType);
1632 }
1633 
1634 /// Perform an operation having the following signature:
1635 ///   void (i8**, i8**)
1636 static void emitARCCopyOperation(CodeGenFunction &CGF,
1637                                  llvm::Value *dst,
1638                                  llvm::Value *src,
1639                                  llvm::Constant *&fn,
1640                                  StringRef fnName) {
1641   assert(dst->getType() == src->getType());
1642 
1643   if (!fn) {
1644     std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
1645     llvm::FunctionType *fnType
1646       = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1647     fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1648   }
1649 
1650   dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1651   src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1652 
1653   llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1654   result->setDoesNotThrow();
1655 }
1656 
1657 /// Produce the code to do a retain.  Based on the type, calls one of:
1658 ///   call i8* @objc_retain(i8* %value)
1659 ///   call i8* @objc_retainBlock(i8* %value)
1660 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1661   if (type->isBlockPointerType())
1662     return EmitARCRetainBlock(value);
1663   else
1664     return EmitARCRetainNonBlock(value);
1665 }
1666 
1667 /// Retain the given object, with normal retain semantics.
1668 ///   call i8* @objc_retain(i8* %value)
1669 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1670   return emitARCValueOperation(*this, value,
1671                                CGM.getARCEntrypoints().objc_retain,
1672                                "objc_retain");
1673 }
1674 
1675 /// Retain the given block, with _Block_copy semantics.
1676 ///   call i8* @objc_retainBlock(i8* %value)
1677 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1678   return emitARCValueOperation(*this, value,
1679                                CGM.getARCEntrypoints().objc_retainBlock,
1680                                "objc_retainBlock");
1681 }
1682 
1683 /// Retain the given object which is the result of a function call.
1684 ///   call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1685 ///
1686 /// Yes, this function name is one character away from a different
1687 /// call with completely different semantics.
1688 llvm::Value *
1689 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1690   // Fetch the void(void) inline asm which marks that we're going to
1691   // retain the autoreleased return value.
1692   llvm::InlineAsm *&marker
1693     = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1694   if (!marker) {
1695     StringRef assembly
1696       = CGM.getTargetCodeGenInfo()
1697            .getARCRetainAutoreleasedReturnValueMarker();
1698 
1699     // If we have an empty assembly string, there's nothing to do.
1700     if (assembly.empty()) {
1701 
1702     // Otherwise, at -O0, build an inline asm that we're going to call
1703     // in a moment.
1704     } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1705       llvm::FunctionType *type =
1706         llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1707                                 /*variadic*/ false);
1708 
1709       marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1710 
1711     // If we're at -O1 and above, we don't want to litter the code
1712     // with this marker yet, so leave a breadcrumb for the ARC
1713     // optimizer to pick up.
1714     } else {
1715       llvm::NamedMDNode *metadata =
1716         CGM.getModule().getOrInsertNamedMetadata(
1717                             "clang.arc.retainAutoreleasedReturnValueMarker");
1718       assert(metadata->getNumOperands() <= 1);
1719       if (metadata->getNumOperands() == 0) {
1720         llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
1721         metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
1722       }
1723     }
1724   }
1725 
1726   // Call the marker asm if we made one, which we do only at -O0.
1727   if (marker) Builder.CreateCall(marker);
1728 
1729   return emitARCValueOperation(*this, value,
1730                      CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1731                                "objc_retainAutoreleasedReturnValue");
1732 }
1733 
1734 /// Release the given object.
1735 ///   call void @objc_release(i8* %value)
1736 void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1737   if (isa<llvm::ConstantPointerNull>(value)) return;
1738 
1739   llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1740   if (!fn) {
1741     std::vector<llvm::Type*> args(1, Int8PtrTy);
1742     llvm::FunctionType *fnType =
1743       llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1744     fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1745   }
1746 
1747   // Cast the argument to 'id'.
1748   value = Builder.CreateBitCast(value, Int8PtrTy);
1749 
1750   // Call objc_release.
1751   llvm::CallInst *call = Builder.CreateCall(fn, value);
1752   call->setDoesNotThrow();
1753 
1754   if (!precise) {
1755     SmallVector<llvm::Value*,1> args;
1756     call->setMetadata("clang.imprecise_release",
1757                       llvm::MDNode::get(Builder.getContext(), args));
1758   }
1759 }
1760 
1761 /// Store into a strong object.  Always calls this:
1762 ///   call void @objc_storeStrong(i8** %addr, i8* %value)
1763 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1764                                                      llvm::Value *value,
1765                                                      bool ignored) {
1766   assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1767            == value->getType());
1768 
1769   llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1770   if (!fn) {
1771     llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
1772     llvm::FunctionType *fnType
1773       = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1774     fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1775   }
1776 
1777   addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1778   llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1779 
1780   Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1781 
1782   if (ignored) return 0;
1783   return value;
1784 }
1785 
1786 /// Store into a strong object.  Sometimes calls this:
1787 ///   call void @objc_storeStrong(i8** %addr, i8* %value)
1788 /// Other times, breaks it down into components.
1789 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
1790                                                  llvm::Value *newValue,
1791                                                  bool ignored) {
1792   QualType type = dst.getType();
1793   bool isBlock = type->isBlockPointerType();
1794 
1795   // Use a store barrier at -O0 unless this is a block type or the
1796   // lvalue is inadequately aligned.
1797   if (shouldUseFusedARCCalls() &&
1798       !isBlock &&
1799       !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1800     return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1801   }
1802 
1803   // Otherwise, split it out.
1804 
1805   // Retain the new value.
1806   newValue = EmitARCRetain(type, newValue);
1807 
1808   // Read the old value.
1809   llvm::Value *oldValue = EmitLoadOfScalar(dst);
1810 
1811   // Store.  We do this before the release so that any deallocs won't
1812   // see the old value.
1813   EmitStoreOfScalar(newValue, dst);
1814 
1815   // Finally, release the old value.
1816   EmitARCRelease(oldValue, /*precise*/ false);
1817 
1818   return newValue;
1819 }
1820 
1821 /// Autorelease the given object.
1822 ///   call i8* @objc_autorelease(i8* %value)
1823 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1824   return emitARCValueOperation(*this, value,
1825                                CGM.getARCEntrypoints().objc_autorelease,
1826                                "objc_autorelease");
1827 }
1828 
1829 /// Autorelease the given object.
1830 ///   call i8* @objc_autoreleaseReturnValue(i8* %value)
1831 llvm::Value *
1832 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1833   return emitARCValueOperation(*this, value,
1834                             CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1835                                "objc_autoreleaseReturnValue");
1836 }
1837 
1838 /// Do a fused retain/autorelease of the given object.
1839 ///   call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1840 llvm::Value *
1841 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1842   return emitARCValueOperation(*this, value,
1843                      CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1844                                "objc_retainAutoreleaseReturnValue");
1845 }
1846 
1847 /// Do a fused retain/autorelease of the given object.
1848 ///   call i8* @objc_retainAutorelease(i8* %value)
1849 /// or
1850 ///   %retain = call i8* @objc_retainBlock(i8* %value)
1851 ///   call i8* @objc_autorelease(i8* %retain)
1852 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1853                                                        llvm::Value *value) {
1854   if (!type->isBlockPointerType())
1855     return EmitARCRetainAutoreleaseNonBlock(value);
1856 
1857   if (isa<llvm::ConstantPointerNull>(value)) return value;
1858 
1859   llvm::Type *origType = value->getType();
1860   value = Builder.CreateBitCast(value, Int8PtrTy);
1861   value = EmitARCRetainBlock(value);
1862   value = EmitARCAutorelease(value);
1863   return Builder.CreateBitCast(value, origType);
1864 }
1865 
1866 /// Do a fused retain/autorelease of the given object.
1867 ///   call i8* @objc_retainAutorelease(i8* %value)
1868 llvm::Value *
1869 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1870   return emitARCValueOperation(*this, value,
1871                                CGM.getARCEntrypoints().objc_retainAutorelease,
1872                                "objc_retainAutorelease");
1873 }
1874 
1875 /// i8* @objc_loadWeak(i8** %addr)
1876 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1877 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1878   return emitARCLoadOperation(*this, addr,
1879                               CGM.getARCEntrypoints().objc_loadWeak,
1880                               "objc_loadWeak");
1881 }
1882 
1883 /// i8* @objc_loadWeakRetained(i8** %addr)
1884 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1885   return emitARCLoadOperation(*this, addr,
1886                               CGM.getARCEntrypoints().objc_loadWeakRetained,
1887                               "objc_loadWeakRetained");
1888 }
1889 
1890 /// i8* @objc_storeWeak(i8** %addr, i8* %value)
1891 /// Returns %value.
1892 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1893                                                llvm::Value *value,
1894                                                bool ignored) {
1895   return emitARCStoreOperation(*this, addr, value,
1896                                CGM.getARCEntrypoints().objc_storeWeak,
1897                                "objc_storeWeak", ignored);
1898 }
1899 
1900 /// i8* @objc_initWeak(i8** %addr, i8* %value)
1901 /// Returns %value.  %addr is known to not have a current weak entry.
1902 /// Essentially equivalent to:
1903 ///   *addr = nil; objc_storeWeak(addr, value);
1904 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1905   // If we're initializing to null, just write null to memory; no need
1906   // to get the runtime involved.  But don't do this if optimization
1907   // is enabled, because accounting for this would make the optimizer
1908   // much more complicated.
1909   if (isa<llvm::ConstantPointerNull>(value) &&
1910       CGM.getCodeGenOpts().OptimizationLevel == 0) {
1911     Builder.CreateStore(value, addr);
1912     return;
1913   }
1914 
1915   emitARCStoreOperation(*this, addr, value,
1916                         CGM.getARCEntrypoints().objc_initWeak,
1917                         "objc_initWeak", /*ignored*/ true);
1918 }
1919 
1920 /// void @objc_destroyWeak(i8** %addr)
1921 /// Essentially objc_storeWeak(addr, nil).
1922 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1923   llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1924   if (!fn) {
1925     std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
1926     llvm::FunctionType *fnType =
1927       llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1928     fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1929   }
1930 
1931   // Cast the argument to 'id*'.
1932   addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1933 
1934   llvm::CallInst *call = Builder.CreateCall(fn, addr);
1935   call->setDoesNotThrow();
1936 }
1937 
1938 /// void @objc_moveWeak(i8** %dest, i8** %src)
1939 /// Disregards the current value in %dest.  Leaves %src pointing to nothing.
1940 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1941 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1942   emitARCCopyOperation(*this, dst, src,
1943                        CGM.getARCEntrypoints().objc_moveWeak,
1944                        "objc_moveWeak");
1945 }
1946 
1947 /// void @objc_copyWeak(i8** %dest, i8** %src)
1948 /// Disregards the current value in %dest.  Essentially
1949 ///   objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1950 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1951   emitARCCopyOperation(*this, dst, src,
1952                        CGM.getARCEntrypoints().objc_copyWeak,
1953                        "objc_copyWeak");
1954 }
1955 
1956 /// Produce the code to do a objc_autoreleasepool_push.
1957 ///   call i8* @objc_autoreleasePoolPush(void)
1958 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1959   llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1960   if (!fn) {
1961     llvm::FunctionType *fnType =
1962       llvm::FunctionType::get(Int8PtrTy, false);
1963     fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1964   }
1965 
1966   llvm::CallInst *call = Builder.CreateCall(fn);
1967   call->setDoesNotThrow();
1968 
1969   return call;
1970 }
1971 
1972 /// Produce the code to do a primitive release.
1973 ///   call void @objc_autoreleasePoolPop(i8* %ptr)
1974 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1975   assert(value->getType() == Int8PtrTy);
1976 
1977   llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1978   if (!fn) {
1979     std::vector<llvm::Type*> args(1, Int8PtrTy);
1980     llvm::FunctionType *fnType =
1981       llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1982 
1983     // We don't want to use a weak import here; instead we should not
1984     // fall into this path.
1985     fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1986   }
1987 
1988   llvm::CallInst *call = Builder.CreateCall(fn, value);
1989   call->setDoesNotThrow();
1990 }
1991 
1992 /// Produce the code to do an MRR version objc_autoreleasepool_push.
1993 /// Which is: [[NSAutoreleasePool alloc] init];
1994 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1995 /// init is declared as: - (id) init; in its NSObject super class.
1996 ///
1997 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1998   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1999   llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2000   // [NSAutoreleasePool alloc]
2001   IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2002   Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2003   CallArgList Args;
2004   RValue AllocRV =
2005     Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2006                                 getContext().getObjCIdType(),
2007                                 AllocSel, Receiver, Args);
2008 
2009   // [Receiver init]
2010   Receiver = AllocRV.getScalarVal();
2011   II = &CGM.getContext().Idents.get("init");
2012   Selector InitSel = getContext().Selectors.getSelector(0, &II);
2013   RValue InitRV =
2014     Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2015                                 getContext().getObjCIdType(),
2016                                 InitSel, Receiver, Args);
2017   return InitRV.getScalarVal();
2018 }
2019 
2020 /// Produce the code to do a primitive release.
2021 /// [tmp drain];
2022 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2023   IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2024   Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2025   CallArgList Args;
2026   CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2027                               getContext().VoidTy, DrainSel, Arg, Args);
2028 }
2029 
2030 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2031                                               llvm::Value *addr,
2032                                               QualType type) {
2033   llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2034   CGF.EmitARCRelease(ptr, /*precise*/ true);
2035 }
2036 
2037 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2038                                                 llvm::Value *addr,
2039                                                 QualType type) {
2040   llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2041   CGF.EmitARCRelease(ptr, /*precise*/ false);
2042 }
2043 
2044 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2045                                      llvm::Value *addr,
2046                                      QualType type) {
2047   CGF.EmitARCDestroyWeak(addr);
2048 }
2049 
2050 namespace {
2051   struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2052     llvm::Value *Token;
2053 
2054     CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2055 
2056     void Emit(CodeGenFunction &CGF, Flags flags) {
2057       CGF.EmitObjCAutoreleasePoolPop(Token);
2058     }
2059   };
2060   struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2061     llvm::Value *Token;
2062 
2063     CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2064 
2065     void Emit(CodeGenFunction &CGF, Flags flags) {
2066       CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2067     }
2068   };
2069 }
2070 
2071 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2072   if (CGM.getLangOptions().ObjCAutoRefCount)
2073     EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2074   else
2075     EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2076 }
2077 
2078 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2079                                                   LValue lvalue,
2080                                                   QualType type) {
2081   switch (type.getObjCLifetime()) {
2082   case Qualifiers::OCL_None:
2083   case Qualifiers::OCL_ExplicitNone:
2084   case Qualifiers::OCL_Strong:
2085   case Qualifiers::OCL_Autoreleasing:
2086     return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
2087                          false);
2088 
2089   case Qualifiers::OCL_Weak:
2090     return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2091                          true);
2092   }
2093 
2094   llvm_unreachable("impossible lifetime!");
2095   return TryEmitResult();
2096 }
2097 
2098 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2099                                                   const Expr *e) {
2100   e = e->IgnoreParens();
2101   QualType type = e->getType();
2102 
2103   // If we're loading retained from a __strong xvalue, we can avoid
2104   // an extra retain/release pair by zeroing out the source of this
2105   // "move" operation.
2106   if (e->isXValue() &&
2107       !type.isConstQualified() &&
2108       type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2109     // Emit the lvalue.
2110     LValue lv = CGF.EmitLValue(e);
2111 
2112     // Load the object pointer.
2113     llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2114 
2115     // Set the source pointer to NULL.
2116     CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2117 
2118     return TryEmitResult(result, true);
2119   }
2120 
2121   // As a very special optimization, in ARC++, if the l-value is the
2122   // result of a non-volatile assignment, do a simple retain of the
2123   // result of the call to objc_storeWeak instead of reloading.
2124   if (CGF.getLangOptions().CPlusPlus &&
2125       !type.isVolatileQualified() &&
2126       type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2127       isa<BinaryOperator>(e) &&
2128       cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2129     return TryEmitResult(CGF.EmitScalarExpr(e), false);
2130 
2131   return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2132 }
2133 
2134 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2135                                            llvm::Value *value);
2136 
2137 /// Given that the given expression is some sort of call (which does
2138 /// not return retained), emit a retain following it.
2139 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2140   llvm::Value *value = CGF.EmitScalarExpr(e);
2141   return emitARCRetainAfterCall(CGF, value);
2142 }
2143 
2144 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2145                                            llvm::Value *value) {
2146   if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2147     CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2148 
2149     // Place the retain immediately following the call.
2150     CGF.Builder.SetInsertPoint(call->getParent(),
2151                                ++llvm::BasicBlock::iterator(call));
2152     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2153 
2154     CGF.Builder.restoreIP(ip);
2155     return value;
2156   } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2157     CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2158 
2159     // Place the retain at the beginning of the normal destination block.
2160     llvm::BasicBlock *BB = invoke->getNormalDest();
2161     CGF.Builder.SetInsertPoint(BB, BB->begin());
2162     value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2163 
2164     CGF.Builder.restoreIP(ip);
2165     return value;
2166 
2167   // Bitcasts can arise because of related-result returns.  Rewrite
2168   // the operand.
2169   } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2170     llvm::Value *operand = bitcast->getOperand(0);
2171     operand = emitARCRetainAfterCall(CGF, operand);
2172     bitcast->setOperand(0, operand);
2173     return bitcast;
2174 
2175   // Generic fall-back case.
2176   } else {
2177     // Retain using the non-block variant: we never need to do a copy
2178     // of a block that's been returned to us.
2179     return CGF.EmitARCRetainNonBlock(value);
2180   }
2181 }
2182 
2183 /// Determine whether it might be important to emit a separate
2184 /// objc_retain_block on the result of the given expression, or
2185 /// whether it's okay to just emit it in a +1 context.
2186 static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2187   assert(e->getType()->isBlockPointerType());
2188   e = e->IgnoreParens();
2189 
2190   // For future goodness, emit block expressions directly in +1
2191   // contexts if we can.
2192   if (isa<BlockExpr>(e))
2193     return false;
2194 
2195   if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2196     switch (cast->getCastKind()) {
2197     // Emitting these operations in +1 contexts is goodness.
2198     case CK_LValueToRValue:
2199     case CK_ARCReclaimReturnedObject:
2200     case CK_ARCConsumeObject:
2201     case CK_ARCProduceObject:
2202       return false;
2203 
2204     // These operations preserve a block type.
2205     case CK_NoOp:
2206     case CK_BitCast:
2207       return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2208 
2209     // These operations are known to be bad (or haven't been considered).
2210     case CK_AnyPointerToBlockPointerCast:
2211     default:
2212       return true;
2213     }
2214   }
2215 
2216   return true;
2217 }
2218 
2219 static TryEmitResult
2220 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
2221   // Look through cleanups.
2222   if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2223     CodeGenFunction::RunCleanupsScope scope(CGF);
2224     return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2225   }
2226 
2227   // The desired result type, if it differs from the type of the
2228   // ultimate opaque expression.
2229   llvm::Type *resultType = 0;
2230 
2231   while (true) {
2232     e = e->IgnoreParens();
2233 
2234     // There's a break at the end of this if-chain;  anything
2235     // that wants to keep looping has to explicitly continue.
2236     if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2237       switch (ce->getCastKind()) {
2238       // No-op casts don't change the type, so we just ignore them.
2239       case CK_NoOp:
2240         e = ce->getSubExpr();
2241         continue;
2242 
2243       case CK_LValueToRValue: {
2244         TryEmitResult loadResult
2245           = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2246         if (resultType) {
2247           llvm::Value *value = loadResult.getPointer();
2248           value = CGF.Builder.CreateBitCast(value, resultType);
2249           loadResult.setPointer(value);
2250         }
2251         return loadResult;
2252       }
2253 
2254       // These casts can change the type, so remember that and
2255       // soldier on.  We only need to remember the outermost such
2256       // cast, though.
2257       case CK_CPointerToObjCPointerCast:
2258       case CK_BlockPointerToObjCPointerCast:
2259       case CK_AnyPointerToBlockPointerCast:
2260       case CK_BitCast:
2261         if (!resultType)
2262           resultType = CGF.ConvertType(ce->getType());
2263         e = ce->getSubExpr();
2264         assert(e->getType()->hasPointerRepresentation());
2265         continue;
2266 
2267       // For consumptions, just emit the subexpression and thus elide
2268       // the retain/release pair.
2269       case CK_ARCConsumeObject: {
2270         llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2271         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2272         return TryEmitResult(result, true);
2273       }
2274 
2275       // Block extends are net +0.  Naively, we could just recurse on
2276       // the subexpression, but actually we need to ensure that the
2277       // value is copied as a block, so there's a little filter here.
2278       case CK_ARCExtendBlockObject: {
2279         llvm::Value *result; // will be a +0 value
2280 
2281         // If we can't safely assume the sub-expression will produce a
2282         // block-copied value, emit the sub-expression at +0.
2283         if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2284           result = CGF.EmitScalarExpr(ce->getSubExpr());
2285 
2286         // Otherwise, try to emit the sub-expression at +1 recursively.
2287         } else {
2288           TryEmitResult subresult
2289             = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2290           result = subresult.getPointer();
2291 
2292           // If that produced a retained value, just use that,
2293           // possibly casting down.
2294           if (subresult.getInt()) {
2295             if (resultType)
2296               result = CGF.Builder.CreateBitCast(result, resultType);
2297             return TryEmitResult(result, true);
2298           }
2299 
2300           // Otherwise it's +0.
2301         }
2302 
2303         // Retain the object as a block, then cast down.
2304         result = CGF.EmitARCRetainBlock(result);
2305         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2306         return TryEmitResult(result, true);
2307       }
2308 
2309       // For reclaims, emit the subexpression as a retained call and
2310       // skip the consumption.
2311       case CK_ARCReclaimReturnedObject: {
2312         llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2313         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2314         return TryEmitResult(result, true);
2315       }
2316 
2317       case CK_GetObjCProperty: {
2318         llvm::Value *result = emitARCRetainCall(CGF, ce);
2319         if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2320         return TryEmitResult(result, true);
2321       }
2322 
2323       default:
2324         break;
2325       }
2326 
2327     // Skip __extension__.
2328     } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2329       if (op->getOpcode() == UO_Extension) {
2330         e = op->getSubExpr();
2331         continue;
2332       }
2333 
2334     // For calls and message sends, use the retained-call logic.
2335     // Delegate inits are a special case in that they're the only
2336     // returns-retained expression that *isn't* surrounded by
2337     // a consume.
2338     } else if (isa<CallExpr>(e) ||
2339                (isa<ObjCMessageExpr>(e) &&
2340                 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2341       llvm::Value *result = emitARCRetainCall(CGF, e);
2342       if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2343       return TryEmitResult(result, true);
2344     }
2345 
2346     // Conservatively halt the search at any other expression kind.
2347     break;
2348   }
2349 
2350   // We didn't find an obvious production, so emit what we've got and
2351   // tell the caller that we didn't manage to retain.
2352   llvm::Value *result = CGF.EmitScalarExpr(e);
2353   if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2354   return TryEmitResult(result, false);
2355 }
2356 
2357 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2358                                                 LValue lvalue,
2359                                                 QualType type) {
2360   TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2361   llvm::Value *value = result.getPointer();
2362   if (!result.getInt())
2363     value = CGF.EmitARCRetain(type, value);
2364   return value;
2365 }
2366 
2367 /// EmitARCRetainScalarExpr - Semantically equivalent to
2368 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2369 /// best-effort attempt to peephole expressions that naturally produce
2370 /// retained objects.
2371 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2372   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2373   llvm::Value *value = result.getPointer();
2374   if (!result.getInt())
2375     value = EmitARCRetain(e->getType(), value);
2376   return value;
2377 }
2378 
2379 llvm::Value *
2380 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2381   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2382   llvm::Value *value = result.getPointer();
2383   if (result.getInt())
2384     value = EmitARCAutorelease(value);
2385   else
2386     value = EmitARCRetainAutorelease(e->getType(), value);
2387   return value;
2388 }
2389 
2390 std::pair<LValue,llvm::Value*>
2391 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2392                                     bool ignored) {
2393   // Evaluate the RHS first.
2394   TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2395   llvm::Value *value = result.getPointer();
2396 
2397   bool hasImmediateRetain = result.getInt();
2398 
2399   // If we didn't emit a retained object, and the l-value is of block
2400   // type, then we need to emit the block-retain immediately in case
2401   // it invalidates the l-value.
2402   if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
2403     value = EmitARCRetainBlock(value);
2404     hasImmediateRetain = true;
2405   }
2406 
2407   LValue lvalue = EmitLValue(e->getLHS());
2408 
2409   // If the RHS was emitted retained, expand this.
2410   if (hasImmediateRetain) {
2411     llvm::Value *oldValue =
2412       EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2413                        lvalue.getAlignment(), e->getType(),
2414                        lvalue.getTBAAInfo());
2415     EmitStoreOfScalar(value, lvalue.getAddress(),
2416                       lvalue.isVolatileQualified(), lvalue.getAlignment(),
2417                       e->getType(), lvalue.getTBAAInfo());
2418     EmitARCRelease(oldValue, /*precise*/ false);
2419   } else {
2420     value = EmitARCStoreStrong(lvalue, value, ignored);
2421   }
2422 
2423   return std::pair<LValue,llvm::Value*>(lvalue, value);
2424 }
2425 
2426 std::pair<LValue,llvm::Value*>
2427 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2428   llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2429   LValue lvalue = EmitLValue(e->getLHS());
2430 
2431   EmitStoreOfScalar(value, lvalue.getAddress(),
2432                     lvalue.isVolatileQualified(), lvalue.getAlignment(),
2433                     e->getType(), lvalue.getTBAAInfo());
2434 
2435   return std::pair<LValue,llvm::Value*>(lvalue, value);
2436 }
2437 
2438 void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2439                                              const ObjCAutoreleasePoolStmt &ARPS) {
2440   const Stmt *subStmt = ARPS.getSubStmt();
2441   const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2442 
2443   CGDebugInfo *DI = getDebugInfo();
2444   if (DI) {
2445     DI->setLocation(S.getLBracLoc());
2446     DI->EmitRegionStart(Builder);
2447   }
2448 
2449   // Keep track of the current cleanup stack depth.
2450   RunCleanupsScope Scope(*this);
2451   if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
2452     llvm::Value *token = EmitObjCAutoreleasePoolPush();
2453     EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2454   } else {
2455     llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2456     EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2457   }
2458 
2459   for (CompoundStmt::const_body_iterator I = S.body_begin(),
2460        E = S.body_end(); I != E; ++I)
2461     EmitStmt(*I);
2462 
2463   if (DI) {
2464     DI->setLocation(S.getRBracLoc());
2465     DI->EmitRegionEnd(Builder);
2466   }
2467 }
2468 
2469 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2470 /// make sure it survives garbage collection until this point.
2471 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2472   // We just use an inline assembly.
2473   llvm::FunctionType *extenderType
2474     = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
2475   llvm::Value *extender
2476     = llvm::InlineAsm::get(extenderType,
2477                            /* assembly */ "",
2478                            /* constraints */ "r",
2479                            /* side effects */ true);
2480 
2481   object = Builder.CreateBitCast(object, VoidPtrTy);
2482   Builder.CreateCall(extender, object)->setDoesNotThrow();
2483 }
2484 
2485 CGObjCRuntime::~CGObjCRuntime() {}
2486