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