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