CGObjC.cpp 104 KB

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