CGObjC.cpp 129 KB

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