CGObjCGNU.cpp 164 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018
  1. //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This provides Objective-C code generation targeting the GNU runtime. The
  10. // class in this file generates structures used by the GNU Objective-C runtime
  11. // library. These structures are defined in objc/objc.h and objc/objc-api.h in
  12. // the GNU runtime distribution.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "CGObjCRuntime.h"
  16. #include "CGCleanup.h"
  17. #include "CodeGenFunction.h"
  18. #include "CodeGenModule.h"
  19. #include "CGCXXABI.h"
  20. #include "clang/CodeGen/ConstantInitBuilder.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/Decl.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/AST/RecordLayout.h"
  25. #include "clang/AST/StmtObjC.h"
  26. #include "clang/Basic/FileManager.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/ADT/StringMap.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/Intrinsics.h"
  32. #include "llvm/IR/LLVMContext.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/Support/Compiler.h"
  35. #include "llvm/Support/ConvertUTF.h"
  36. #include <cctype>
  37. using namespace clang;
  38. using namespace CodeGen;
  39. namespace {
  40. std::string SymbolNameForMethod( StringRef ClassName,
  41. StringRef CategoryName, const Selector MethodName,
  42. bool isClassMethod) {
  43. std::string MethodNameColonStripped = MethodName.getAsString();
  44. std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
  45. ':', '_');
  46. return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
  47. CategoryName + "_" + MethodNameColonStripped).str();
  48. }
  49. /// Class that lazily initialises the runtime function. Avoids inserting the
  50. /// types and the function declaration into a module if they're not used, and
  51. /// avoids constructing the type more than once if it's used more than once.
  52. class LazyRuntimeFunction {
  53. CodeGenModule *CGM;
  54. llvm::FunctionType *FTy;
  55. const char *FunctionName;
  56. llvm::Constant *Function;
  57. public:
  58. /// Constructor leaves this class uninitialized, because it is intended to
  59. /// be used as a field in another class and not all of the types that are
  60. /// used as arguments will necessarily be available at construction time.
  61. LazyRuntimeFunction()
  62. : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
  63. /// Initialises the lazy function with the name, return type, and the types
  64. /// of the arguments.
  65. template <typename... Tys>
  66. void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
  67. Tys *... Types) {
  68. CGM = Mod;
  69. FunctionName = name;
  70. Function = nullptr;
  71. if(sizeof...(Tys)) {
  72. SmallVector<llvm::Type *, 8> ArgTys({Types...});
  73. FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
  74. }
  75. else {
  76. FTy = llvm::FunctionType::get(RetTy, None, false);
  77. }
  78. }
  79. llvm::FunctionType *getType() { return FTy; }
  80. /// Overloaded cast operator, allows the class to be implicitly cast to an
  81. /// LLVM constant.
  82. operator llvm::Constant *() {
  83. if (!Function) {
  84. if (!FunctionName)
  85. return nullptr;
  86. Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
  87. }
  88. return Function;
  89. }
  90. operator llvm::Function *() {
  91. return cast<llvm::Function>((llvm::Constant *)*this);
  92. }
  93. };
  94. /// GNU Objective-C runtime code generation. This class implements the parts of
  95. /// Objective-C support that are specific to the GNU family of runtimes (GCC,
  96. /// GNUstep and ObjFW).
  97. class CGObjCGNU : public CGObjCRuntime {
  98. protected:
  99. /// The LLVM module into which output is inserted
  100. llvm::Module &TheModule;
  101. /// strut objc_super. Used for sending messages to super. This structure
  102. /// contains the receiver (object) and the expected class.
  103. llvm::StructType *ObjCSuperTy;
  104. /// struct objc_super*. The type of the argument to the superclass message
  105. /// lookup functions.
  106. llvm::PointerType *PtrToObjCSuperTy;
  107. /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
  108. /// SEL is included in a header somewhere, in which case it will be whatever
  109. /// type is declared in that header, most likely {i8*, i8*}.
  110. llvm::PointerType *SelectorTy;
  111. /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
  112. /// places where it's used
  113. llvm::IntegerType *Int8Ty;
  114. /// Pointer to i8 - LLVM type of char*, for all of the places where the
  115. /// runtime needs to deal with C strings.
  116. llvm::PointerType *PtrToInt8Ty;
  117. /// struct objc_protocol type
  118. llvm::StructType *ProtocolTy;
  119. /// Protocol * type.
  120. llvm::PointerType *ProtocolPtrTy;
  121. /// Instance Method Pointer type. This is a pointer to a function that takes,
  122. /// at a minimum, an object and a selector, and is the generic type for
  123. /// Objective-C methods. Due to differences between variadic / non-variadic
  124. /// calling conventions, it must always be cast to the correct type before
  125. /// actually being used.
  126. llvm::PointerType *IMPTy;
  127. /// Type of an untyped Objective-C object. Clang treats id as a built-in type
  128. /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
  129. /// but if the runtime header declaring it is included then it may be a
  130. /// pointer to a structure.
  131. llvm::PointerType *IdTy;
  132. /// Pointer to a pointer to an Objective-C object. Used in the new ABI
  133. /// message lookup function and some GC-related functions.
  134. llvm::PointerType *PtrToIdTy;
  135. /// The clang type of id. Used when using the clang CGCall infrastructure to
  136. /// call Objective-C methods.
  137. CanQualType ASTIdTy;
  138. /// LLVM type for C int type.
  139. llvm::IntegerType *IntTy;
  140. /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
  141. /// used in the code to document the difference between i8* meaning a pointer
  142. /// to a C string and i8* meaning a pointer to some opaque type.
  143. llvm::PointerType *PtrTy;
  144. /// LLVM type for C long type. The runtime uses this in a lot of places where
  145. /// it should be using intptr_t, but we can't fix this without breaking
  146. /// compatibility with GCC...
  147. llvm::IntegerType *LongTy;
  148. /// LLVM type for C size_t. Used in various runtime data structures.
  149. llvm::IntegerType *SizeTy;
  150. /// LLVM type for C intptr_t.
  151. llvm::IntegerType *IntPtrTy;
  152. /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
  153. llvm::IntegerType *PtrDiffTy;
  154. /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
  155. /// variables.
  156. llvm::PointerType *PtrToIntTy;
  157. /// LLVM type for Objective-C BOOL type.
  158. llvm::Type *BoolTy;
  159. /// 32-bit integer type, to save us needing to look it up every time it's used.
  160. llvm::IntegerType *Int32Ty;
  161. /// 64-bit integer type, to save us needing to look it up every time it's used.
  162. llvm::IntegerType *Int64Ty;
  163. /// The type of struct objc_property.
  164. llvm::StructType *PropertyMetadataTy;
  165. /// Metadata kind used to tie method lookups to message sends. The GNUstep
  166. /// runtime provides some LLVM passes that can use this to do things like
  167. /// automatic IMP caching and speculative inlining.
  168. unsigned msgSendMDKind;
  169. /// Does the current target use SEH-based exceptions? False implies
  170. /// Itanium-style DWARF unwinding.
  171. bool usesSEHExceptions;
  172. /// Helper to check if we are targeting a specific runtime version or later.
  173. bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
  174. const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
  175. return (R.getKind() == kind) &&
  176. (R.getVersion() >= VersionTuple(major, minor));
  177. }
  178. std::string SymbolForProtocol(StringRef Name) {
  179. return (StringRef("._OBJC_PROTOCOL_") + Name).str();
  180. }
  181. std::string SymbolForProtocolRef(StringRef Name) {
  182. return (StringRef("._OBJC_REF_PROTOCOL_") + Name).str();
  183. }
  184. /// Helper function that generates a constant string and returns a pointer to
  185. /// the start of the string. The result of this function can be used anywhere
  186. /// where the C code specifies const char*.
  187. llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
  188. ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
  189. return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
  190. Array.getPointer(), Zeros);
  191. }
  192. /// Emits a linkonce_odr string, whose name is the prefix followed by the
  193. /// string value. This allows the linker to combine the strings between
  194. /// different modules. Used for EH typeinfo names, selector strings, and a
  195. /// few other things.
  196. llvm::Constant *ExportUniqueString(const std::string &Str,
  197. const std::string &prefix,
  198. bool Private=false) {
  199. std::string name = prefix + Str;
  200. auto *ConstStr = TheModule.getGlobalVariable(name);
  201. if (!ConstStr) {
  202. llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
  203. auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
  204. llvm::GlobalValue::LinkOnceODRLinkage, value, name);
  205. GV->setComdat(TheModule.getOrInsertComdat(name));
  206. if (Private)
  207. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  208. ConstStr = GV;
  209. }
  210. return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
  211. ConstStr, Zeros);
  212. }
  213. /// Returns a property name and encoding string.
  214. llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
  215. const Decl *Container) {
  216. assert(!isRuntime(ObjCRuntime::GNUstep, 2));
  217. if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
  218. std::string NameAndAttributes;
  219. std::string TypeStr =
  220. CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
  221. NameAndAttributes += '\0';
  222. NameAndAttributes += TypeStr.length() + 3;
  223. NameAndAttributes += TypeStr;
  224. NameAndAttributes += '\0';
  225. NameAndAttributes += PD->getNameAsString();
  226. return MakeConstantString(NameAndAttributes);
  227. }
  228. return MakeConstantString(PD->getNameAsString());
  229. }
  230. /// Push the property attributes into two structure fields.
  231. void PushPropertyAttributes(ConstantStructBuilder &Fields,
  232. const ObjCPropertyDecl *property, bool isSynthesized=true, bool
  233. isDynamic=true) {
  234. int attrs = property->getPropertyAttributes();
  235. // For read-only properties, clear the copy and retain flags
  236. if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
  237. attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
  238. attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
  239. attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
  240. attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
  241. }
  242. // The first flags field has the same attribute values as clang uses internally
  243. Fields.addInt(Int8Ty, attrs & 0xff);
  244. attrs >>= 8;
  245. attrs <<= 2;
  246. // For protocol properties, synthesized and dynamic have no meaning, so we
  247. // reuse these flags to indicate that this is a protocol property (both set
  248. // has no meaning, as a property can't be both synthesized and dynamic)
  249. attrs |= isSynthesized ? (1<<0) : 0;
  250. attrs |= isDynamic ? (1<<1) : 0;
  251. // The second field is the next four fields left shifted by two, with the
  252. // low bit set to indicate whether the field is synthesized or dynamic.
  253. Fields.addInt(Int8Ty, attrs & 0xff);
  254. // Two padding fields
  255. Fields.addInt(Int8Ty, 0);
  256. Fields.addInt(Int8Ty, 0);
  257. }
  258. virtual llvm::Constant *GenerateCategoryProtocolList(const
  259. ObjCCategoryDecl *OCD);
  260. virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
  261. int count) {
  262. // int count;
  263. Fields.addInt(IntTy, count);
  264. // int size; (only in GNUstep v2 ABI.
  265. if (isRuntime(ObjCRuntime::GNUstep, 2)) {
  266. llvm::DataLayout td(&TheModule);
  267. Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
  268. CGM.getContext().getCharWidth());
  269. }
  270. // struct objc_property_list *next;
  271. Fields.add(NULLPtr);
  272. // struct objc_property properties[]
  273. return Fields.beginArray(PropertyMetadataTy);
  274. }
  275. virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
  276. const ObjCPropertyDecl *property,
  277. const Decl *OCD,
  278. bool isSynthesized=true, bool
  279. isDynamic=true) {
  280. auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
  281. ASTContext &Context = CGM.getContext();
  282. Fields.add(MakePropertyEncodingString(property, OCD));
  283. PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
  284. auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
  285. if (accessor) {
  286. std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
  287. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  288. Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
  289. Fields.add(TypeEncoding);
  290. } else {
  291. Fields.add(NULLPtr);
  292. Fields.add(NULLPtr);
  293. }
  294. };
  295. addPropertyMethod(property->getGetterMethodDecl());
  296. addPropertyMethod(property->getSetterMethodDecl());
  297. Fields.finishAndAddTo(PropertiesArray);
  298. }
  299. /// Ensures that the value has the required type, by inserting a bitcast if
  300. /// required. This function lets us avoid inserting bitcasts that are
  301. /// redundant.
  302. llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
  303. if (V->getType() == Ty) return V;
  304. return B.CreateBitCast(V, Ty);
  305. }
  306. Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
  307. if (V.getType() == Ty) return V;
  308. return B.CreateBitCast(V, Ty);
  309. }
  310. // Some zeros used for GEPs in lots of places.
  311. llvm::Constant *Zeros[2];
  312. /// Null pointer value. Mainly used as a terminator in various arrays.
  313. llvm::Constant *NULLPtr;
  314. /// LLVM context.
  315. llvm::LLVMContext &VMContext;
  316. protected:
  317. /// Placeholder for the class. Lots of things refer to the class before we've
  318. /// actually emitted it. We use this alias as a placeholder, and then replace
  319. /// it with a pointer to the class structure before finally emitting the
  320. /// module.
  321. llvm::GlobalAlias *ClassPtrAlias;
  322. /// Placeholder for the metaclass. Lots of things refer to the class before
  323. /// we've / actually emitted it. We use this alias as a placeholder, and then
  324. /// replace / it with a pointer to the metaclass structure before finally
  325. /// emitting the / module.
  326. llvm::GlobalAlias *MetaClassPtrAlias;
  327. /// All of the classes that have been generated for this compilation units.
  328. std::vector<llvm::Constant*> Classes;
  329. /// All of the categories that have been generated for this compilation units.
  330. std::vector<llvm::Constant*> Categories;
  331. /// All of the Objective-C constant strings that have been generated for this
  332. /// compilation units.
  333. std::vector<llvm::Constant*> ConstantStrings;
  334. /// Map from string values to Objective-C constant strings in the output.
  335. /// Used to prevent emitting Objective-C strings more than once. This should
  336. /// not be required at all - CodeGenModule should manage this list.
  337. llvm::StringMap<llvm::Constant*> ObjCStrings;
  338. /// All of the protocols that have been declared.
  339. llvm::StringMap<llvm::Constant*> ExistingProtocols;
  340. /// For each variant of a selector, we store the type encoding and a
  341. /// placeholder value. For an untyped selector, the type will be the empty
  342. /// string. Selector references are all done via the module's selector table,
  343. /// so we create an alias as a placeholder and then replace it with the real
  344. /// value later.
  345. typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
  346. /// Type of the selector map. This is roughly equivalent to the structure
  347. /// used in the GNUstep runtime, which maintains a list of all of the valid
  348. /// types for a selector in a table.
  349. typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
  350. SelectorMap;
  351. /// A map from selectors to selector types. This allows us to emit all
  352. /// selectors of the same name and type together.
  353. SelectorMap SelectorTable;
  354. /// Selectors related to memory management. When compiling in GC mode, we
  355. /// omit these.
  356. Selector RetainSel, ReleaseSel, AutoreleaseSel;
  357. /// Runtime functions used for memory management in GC mode. Note that clang
  358. /// supports code generation for calling these functions, but neither GNU
  359. /// runtime actually supports this API properly yet.
  360. LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
  361. WeakAssignFn, GlobalAssignFn;
  362. typedef std::pair<std::string, std::string> ClassAliasPair;
  363. /// All classes that have aliases set for them.
  364. std::vector<ClassAliasPair> ClassAliases;
  365. protected:
  366. /// Function used for throwing Objective-C exceptions.
  367. LazyRuntimeFunction ExceptionThrowFn;
  368. /// Function used for rethrowing exceptions, used at the end of \@finally or
  369. /// \@synchronize blocks.
  370. LazyRuntimeFunction ExceptionReThrowFn;
  371. /// Function called when entering a catch function. This is required for
  372. /// differentiating Objective-C exceptions and foreign exceptions.
  373. LazyRuntimeFunction EnterCatchFn;
  374. /// Function called when exiting from a catch block. Used to do exception
  375. /// cleanup.
  376. LazyRuntimeFunction ExitCatchFn;
  377. /// Function called when entering an \@synchronize block. Acquires the lock.
  378. LazyRuntimeFunction SyncEnterFn;
  379. /// Function called when exiting an \@synchronize block. Releases the lock.
  380. LazyRuntimeFunction SyncExitFn;
  381. private:
  382. /// Function called if fast enumeration detects that the collection is
  383. /// modified during the update.
  384. LazyRuntimeFunction EnumerationMutationFn;
  385. /// Function for implementing synthesized property getters that return an
  386. /// object.
  387. LazyRuntimeFunction GetPropertyFn;
  388. /// Function for implementing synthesized property setters that return an
  389. /// object.
  390. LazyRuntimeFunction SetPropertyFn;
  391. /// Function used for non-object declared property getters.
  392. LazyRuntimeFunction GetStructPropertyFn;
  393. /// Function used for non-object declared property setters.
  394. LazyRuntimeFunction SetStructPropertyFn;
  395. protected:
  396. /// The version of the runtime that this class targets. Must match the
  397. /// version in the runtime.
  398. int RuntimeVersion;
  399. /// The version of the protocol class. Used to differentiate between ObjC1
  400. /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
  401. /// components and can not contain declared properties. We always emit
  402. /// Objective-C 2 property structures, but we have to pretend that they're
  403. /// Objective-C 1 property structures when targeting the GCC runtime or it
  404. /// will abort.
  405. const int ProtocolVersion;
  406. /// The version of the class ABI. This value is used in the class structure
  407. /// and indicates how various fields should be interpreted.
  408. const int ClassABIVersion;
  409. /// Generates an instance variable list structure. This is a structure
  410. /// containing a size and an array of structures containing instance variable
  411. /// metadata. This is used purely for introspection in the fragile ABI. In
  412. /// the non-fragile ABI, it's used for instance variable fixup.
  413. virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
  414. ArrayRef<llvm::Constant *> IvarTypes,
  415. ArrayRef<llvm::Constant *> IvarOffsets,
  416. ArrayRef<llvm::Constant *> IvarAlign,
  417. ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
  418. /// Generates a method list structure. This is a structure containing a size
  419. /// and an array of structures containing method metadata.
  420. ///
  421. /// This structure is used by both classes and categories, and contains a next
  422. /// pointer allowing them to be chained together in a linked list.
  423. llvm::Constant *GenerateMethodList(StringRef ClassName,
  424. StringRef CategoryName,
  425. ArrayRef<const ObjCMethodDecl*> Methods,
  426. bool isClassMethodList);
  427. /// Emits an empty protocol. This is used for \@protocol() where no protocol
  428. /// is found. The runtime will (hopefully) fix up the pointer to refer to the
  429. /// real protocol.
  430. virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
  431. /// Generates a list of property metadata structures. This follows the same
  432. /// pattern as method and instance variable metadata lists.
  433. llvm::Constant *GeneratePropertyList(const Decl *Container,
  434. const ObjCContainerDecl *OCD,
  435. bool isClassProperty=false,
  436. bool protocolOptionalProperties=false);
  437. /// Generates a list of referenced protocols. Classes, categories, and
  438. /// protocols all use this structure.
  439. llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
  440. /// To ensure that all protocols are seen by the runtime, we add a category on
  441. /// a class defined in the runtime, declaring no methods, but adopting the
  442. /// protocols. This is a horribly ugly hack, but it allows us to collect all
  443. /// of the protocols without changing the ABI.
  444. void GenerateProtocolHolderCategory();
  445. /// Generates a class structure.
  446. llvm::Constant *GenerateClassStructure(
  447. llvm::Constant *MetaClass,
  448. llvm::Constant *SuperClass,
  449. unsigned info,
  450. const char *Name,
  451. llvm::Constant *Version,
  452. llvm::Constant *InstanceSize,
  453. llvm::Constant *IVars,
  454. llvm::Constant *Methods,
  455. llvm::Constant *Protocols,
  456. llvm::Constant *IvarOffsets,
  457. llvm::Constant *Properties,
  458. llvm::Constant *StrongIvarBitmap,
  459. llvm::Constant *WeakIvarBitmap,
  460. bool isMeta=false);
  461. /// Generates a method list. This is used by protocols to define the required
  462. /// and optional methods.
  463. virtual llvm::Constant *GenerateProtocolMethodList(
  464. ArrayRef<const ObjCMethodDecl*> Methods);
  465. /// Emits optional and required method lists.
  466. template<class T>
  467. void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
  468. llvm::Constant *&Optional) {
  469. SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
  470. SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
  471. for (const auto *I : Methods)
  472. if (I->isOptional())
  473. OptionalMethods.push_back(I);
  474. else
  475. RequiredMethods.push_back(I);
  476. Required = GenerateProtocolMethodList(RequiredMethods);
  477. Optional = GenerateProtocolMethodList(OptionalMethods);
  478. }
  479. /// Returns a selector with the specified type encoding. An empty string is
  480. /// used to return an untyped selector (with the types field set to NULL).
  481. virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
  482. const std::string &TypeEncoding);
  483. /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
  484. /// contains the class and ivar names, in the v2 ABI this contains the type
  485. /// encoding as well.
  486. virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
  487. const ObjCIvarDecl *Ivar) {
  488. const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
  489. + '.' + Ivar->getNameAsString();
  490. return Name;
  491. }
  492. /// Returns the variable used to store the offset of an instance variable.
  493. llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
  494. const ObjCIvarDecl *Ivar);
  495. /// Emits a reference to a class. This allows the linker to object if there
  496. /// is no class of the matching name.
  497. void EmitClassRef(const std::string &className);
  498. /// Emits a pointer to the named class
  499. virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
  500. const std::string &Name, bool isWeak);
  501. /// Looks up the method for sending a message to the specified object. This
  502. /// mechanism differs between the GCC and GNU runtimes, so this method must be
  503. /// overridden in subclasses.
  504. virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
  505. llvm::Value *&Receiver,
  506. llvm::Value *cmd,
  507. llvm::MDNode *node,
  508. MessageSendInfo &MSI) = 0;
  509. /// Looks up the method for sending a message to a superclass. This
  510. /// mechanism differs between the GCC and GNU runtimes, so this method must
  511. /// be overridden in subclasses.
  512. virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
  513. Address ObjCSuper,
  514. llvm::Value *cmd,
  515. MessageSendInfo &MSI) = 0;
  516. /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
  517. /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
  518. /// bits set to their values, LSB first, while larger ones are stored in a
  519. /// structure of this / form:
  520. ///
  521. /// struct { int32_t length; int32_t values[length]; };
  522. ///
  523. /// The values in the array are stored in host-endian format, with the least
  524. /// significant bit being assumed to come first in the bitfield. Therefore,
  525. /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
  526. /// while a bitfield / with the 63rd bit set will be 1<<64.
  527. llvm::Constant *MakeBitField(ArrayRef<bool> bits);
  528. public:
  529. CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
  530. unsigned protocolClassVersion, unsigned classABI=1);
  531. ConstantAddress GenerateConstantString(const StringLiteral *) override;
  532. RValue
  533. GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
  534. QualType ResultType, Selector Sel,
  535. llvm::Value *Receiver, const CallArgList &CallArgs,
  536. const ObjCInterfaceDecl *Class,
  537. const ObjCMethodDecl *Method) override;
  538. RValue
  539. GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
  540. QualType ResultType, Selector Sel,
  541. const ObjCInterfaceDecl *Class,
  542. bool isCategoryImpl, llvm::Value *Receiver,
  543. bool IsClassMessage, const CallArgList &CallArgs,
  544. const ObjCMethodDecl *Method) override;
  545. llvm::Value *GetClass(CodeGenFunction &CGF,
  546. const ObjCInterfaceDecl *OID) override;
  547. llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
  548. Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
  549. llvm::Value *GetSelector(CodeGenFunction &CGF,
  550. const ObjCMethodDecl *Method) override;
  551. virtual llvm::Constant *GetConstantSelector(Selector Sel,
  552. const std::string &TypeEncoding) {
  553. llvm_unreachable("Runtime unable to generate constant selector");
  554. }
  555. llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
  556. return GetConstantSelector(M->getSelector(),
  557. CGM.getContext().getObjCEncodingForMethodDecl(M));
  558. }
  559. llvm::Constant *GetEHType(QualType T) override;
  560. llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
  561. const ObjCContainerDecl *CD) override;
  562. void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
  563. void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
  564. void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
  565. llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
  566. const ObjCProtocolDecl *PD) override;
  567. void GenerateProtocol(const ObjCProtocolDecl *PD) override;
  568. llvm::Function *ModuleInitFunction() override;
  569. llvm::Constant *GetPropertyGetFunction() override;
  570. llvm::Constant *GetPropertySetFunction() override;
  571. llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
  572. bool copy) override;
  573. llvm::Constant *GetSetStructFunction() override;
  574. llvm::Constant *GetGetStructFunction() override;
  575. llvm::Constant *GetCppAtomicObjectGetFunction() override;
  576. llvm::Constant *GetCppAtomicObjectSetFunction() override;
  577. llvm::Constant *EnumerationMutationFunction() override;
  578. void EmitTryStmt(CodeGenFunction &CGF,
  579. const ObjCAtTryStmt &S) override;
  580. void EmitSynchronizedStmt(CodeGenFunction &CGF,
  581. const ObjCAtSynchronizedStmt &S) override;
  582. void EmitThrowStmt(CodeGenFunction &CGF,
  583. const ObjCAtThrowStmt &S,
  584. bool ClearInsertionPoint=true) override;
  585. llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
  586. Address AddrWeakObj) override;
  587. void EmitObjCWeakAssign(CodeGenFunction &CGF,
  588. llvm::Value *src, Address dst) override;
  589. void EmitObjCGlobalAssign(CodeGenFunction &CGF,
  590. llvm::Value *src, Address dest,
  591. bool threadlocal=false) override;
  592. void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
  593. Address dest, llvm::Value *ivarOffset) override;
  594. void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
  595. llvm::Value *src, Address dest) override;
  596. void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
  597. Address SrcPtr,
  598. llvm::Value *Size) override;
  599. LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
  600. llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
  601. unsigned CVRQualifiers) override;
  602. llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
  603. const ObjCInterfaceDecl *Interface,
  604. const ObjCIvarDecl *Ivar) override;
  605. llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
  606. llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
  607. const CGBlockInfo &blockInfo) override {
  608. return NULLPtr;
  609. }
  610. llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
  611. const CGBlockInfo &blockInfo) override {
  612. return NULLPtr;
  613. }
  614. llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
  615. return NULLPtr;
  616. }
  617. };
  618. /// Class representing the legacy GCC Objective-C ABI. This is the default when
  619. /// -fobjc-nonfragile-abi is not specified.
  620. ///
  621. /// The GCC ABI target actually generates code that is approximately compatible
  622. /// with the new GNUstep runtime ABI, but refrains from using any features that
  623. /// would not work with the GCC runtime. For example, clang always generates
  624. /// the extended form of the class structure, and the extra fields are simply
  625. /// ignored by GCC libobjc.
  626. class CGObjCGCC : public CGObjCGNU {
  627. /// The GCC ABI message lookup function. Returns an IMP pointing to the
  628. /// method implementation for this message.
  629. LazyRuntimeFunction MsgLookupFn;
  630. /// The GCC ABI superclass message lookup function. Takes a pointer to a
  631. /// structure describing the receiver and the class, and a selector as
  632. /// arguments. Returns the IMP for the corresponding method.
  633. LazyRuntimeFunction MsgLookupSuperFn;
  634. protected:
  635. llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
  636. llvm::Value *cmd, llvm::MDNode *node,
  637. MessageSendInfo &MSI) override {
  638. CGBuilderTy &Builder = CGF.Builder;
  639. llvm::Value *args[] = {
  640. EnforceType(Builder, Receiver, IdTy),
  641. EnforceType(Builder, cmd, SelectorTy) };
  642. llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
  643. imp->setMetadata(msgSendMDKind, node);
  644. return imp;
  645. }
  646. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  647. llvm::Value *cmd, MessageSendInfo &MSI) override {
  648. CGBuilderTy &Builder = CGF.Builder;
  649. llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
  650. PtrToObjCSuperTy).getPointer(), cmd};
  651. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
  652. }
  653. public:
  654. CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
  655. // IMP objc_msg_lookup(id, SEL);
  656. MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
  657. // IMP objc_msg_lookup_super(struct objc_super*, SEL);
  658. MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
  659. PtrToObjCSuperTy, SelectorTy);
  660. }
  661. };
  662. /// Class used when targeting the new GNUstep runtime ABI.
  663. class CGObjCGNUstep : public CGObjCGNU {
  664. /// The slot lookup function. Returns a pointer to a cacheable structure
  665. /// that contains (among other things) the IMP.
  666. LazyRuntimeFunction SlotLookupFn;
  667. /// The GNUstep ABI superclass message lookup function. Takes a pointer to
  668. /// a structure describing the receiver and the class, and a selector as
  669. /// arguments. Returns the slot for the corresponding method. Superclass
  670. /// message lookup rarely changes, so this is a good caching opportunity.
  671. LazyRuntimeFunction SlotLookupSuperFn;
  672. /// Specialised function for setting atomic retain properties
  673. LazyRuntimeFunction SetPropertyAtomic;
  674. /// Specialised function for setting atomic copy properties
  675. LazyRuntimeFunction SetPropertyAtomicCopy;
  676. /// Specialised function for setting nonatomic retain properties
  677. LazyRuntimeFunction SetPropertyNonAtomic;
  678. /// Specialised function for setting nonatomic copy properties
  679. LazyRuntimeFunction SetPropertyNonAtomicCopy;
  680. /// Function to perform atomic copies of C++ objects with nontrivial copy
  681. /// constructors from Objective-C ivars.
  682. LazyRuntimeFunction CxxAtomicObjectGetFn;
  683. /// Function to perform atomic copies of C++ objects with nontrivial copy
  684. /// constructors to Objective-C ivars.
  685. LazyRuntimeFunction CxxAtomicObjectSetFn;
  686. /// Type of an slot structure pointer. This is returned by the various
  687. /// lookup functions.
  688. llvm::Type *SlotTy;
  689. public:
  690. llvm::Constant *GetEHType(QualType T) override;
  691. protected:
  692. llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
  693. llvm::Value *cmd, llvm::MDNode *node,
  694. MessageSendInfo &MSI) override {
  695. CGBuilderTy &Builder = CGF.Builder;
  696. llvm::Function *LookupFn = SlotLookupFn;
  697. // Store the receiver on the stack so that we can reload it later
  698. Address ReceiverPtr =
  699. CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
  700. Builder.CreateStore(Receiver, ReceiverPtr);
  701. llvm::Value *self;
  702. if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
  703. self = CGF.LoadObjCSelf();
  704. } else {
  705. self = llvm::ConstantPointerNull::get(IdTy);
  706. }
  707. // The lookup function is guaranteed not to capture the receiver pointer.
  708. LookupFn->addParamAttr(0, llvm::Attribute::NoCapture);
  709. llvm::Value *args[] = {
  710. EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
  711. EnforceType(Builder, cmd, SelectorTy),
  712. EnforceType(Builder, self, IdTy) };
  713. llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
  714. slot->setOnlyReadsMemory();
  715. slot->setMetadata(msgSendMDKind, node);
  716. // Load the imp from the slot
  717. llvm::Value *imp = Builder.CreateAlignedLoad(
  718. Builder.CreateStructGEP(nullptr, slot, 4), CGF.getPointerAlign());
  719. // The lookup function may have changed the receiver, so make sure we use
  720. // the new one.
  721. Receiver = Builder.CreateLoad(ReceiverPtr, true);
  722. return imp;
  723. }
  724. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  725. llvm::Value *cmd,
  726. MessageSendInfo &MSI) override {
  727. CGBuilderTy &Builder = CGF.Builder;
  728. llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
  729. llvm::CallInst *slot =
  730. CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
  731. slot->setOnlyReadsMemory();
  732. return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
  733. CGF.getPointerAlign());
  734. }
  735. public:
  736. CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
  737. CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
  738. unsigned ClassABI) :
  739. CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
  740. const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
  741. llvm::StructType *SlotStructTy =
  742. llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
  743. SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
  744. // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
  745. SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
  746. SelectorTy, IdTy);
  747. // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
  748. SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  749. PtrToObjCSuperTy, SelectorTy);
  750. // If we're in ObjC++ mode, then we want to make
  751. if (usesSEHExceptions) {
  752. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  753. // void objc_exception_rethrow(void)
  754. ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
  755. } else if (CGM.getLangOpts().CPlusPlus) {
  756. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  757. // void *__cxa_begin_catch(void *e)
  758. EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
  759. // void __cxa_end_catch(void)
  760. ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
  761. // void _Unwind_Resume_or_Rethrow(void*)
  762. ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
  763. PtrTy);
  764. } else if (R.getVersion() >= VersionTuple(1, 7)) {
  765. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  766. // id objc_begin_catch(void *e)
  767. EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
  768. // void objc_end_catch(void)
  769. ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
  770. // void _Unwind_Resume_or_Rethrow(void*)
  771. ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
  772. }
  773. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  774. SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
  775. SelectorTy, IdTy, PtrDiffTy);
  776. SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
  777. IdTy, SelectorTy, IdTy, PtrDiffTy);
  778. SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
  779. IdTy, SelectorTy, IdTy, PtrDiffTy);
  780. SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
  781. VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
  782. // void objc_setCppObjectAtomic(void *dest, const void *src, void
  783. // *helper);
  784. CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
  785. PtrTy, PtrTy);
  786. // void objc_getCppObjectAtomic(void *dest, const void *src, void
  787. // *helper);
  788. CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
  789. PtrTy, PtrTy);
  790. }
  791. llvm::Constant *GetCppAtomicObjectGetFunction() override {
  792. // The optimised functions were added in version 1.7 of the GNUstep
  793. // runtime.
  794. assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
  795. VersionTuple(1, 7));
  796. return CxxAtomicObjectGetFn;
  797. }
  798. llvm::Constant *GetCppAtomicObjectSetFunction() override {
  799. // The optimised functions were added in version 1.7 of the GNUstep
  800. // runtime.
  801. assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
  802. VersionTuple(1, 7));
  803. return CxxAtomicObjectSetFn;
  804. }
  805. llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
  806. bool copy) override {
  807. // The optimised property functions omit the GC check, and so are not
  808. // safe to use in GC mode. The standard functions are fast in GC mode,
  809. // so there is less advantage in using them.
  810. assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
  811. // The optimised functions were added in version 1.7 of the GNUstep
  812. // runtime.
  813. assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
  814. VersionTuple(1, 7));
  815. if (atomic) {
  816. if (copy) return SetPropertyAtomicCopy;
  817. return SetPropertyAtomic;
  818. }
  819. return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
  820. }
  821. };
  822. /// GNUstep Objective-C ABI version 2 implementation.
  823. /// This is the ABI that provides a clean break with the legacy GCC ABI and
  824. /// cleans up a number of things that were added to work around 1980s linkers.
  825. class CGObjCGNUstep2 : public CGObjCGNUstep {
  826. enum SectionKind
  827. {
  828. SelectorSection = 0,
  829. ClassSection,
  830. ClassReferenceSection,
  831. CategorySection,
  832. ProtocolSection,
  833. ProtocolReferenceSection,
  834. ClassAliasSection,
  835. ConstantStringSection
  836. };
  837. static const char *const SectionsBaseNames[8];
  838. template<SectionKind K>
  839. std::string sectionName() {
  840. std::string name(SectionsBaseNames[K]);
  841. if (CGM.getTriple().isOSBinFormatCOFF())
  842. name += "$m";
  843. return name;
  844. }
  845. /// The GCC ABI superclass message lookup function. Takes a pointer to a
  846. /// structure describing the receiver and the class, and a selector as
  847. /// arguments. Returns the IMP for the corresponding method.
  848. LazyRuntimeFunction MsgLookupSuperFn;
  849. /// A flag indicating if we've emitted at least one protocol.
  850. /// If we haven't, then we need to emit an empty protocol, to ensure that the
  851. /// __start__objc_protocols and __stop__objc_protocols sections exist.
  852. bool EmittedProtocol = false;
  853. /// A flag indicating if we've emitted at least one protocol reference.
  854. /// If we haven't, then we need to emit an empty protocol, to ensure that the
  855. /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
  856. /// exist.
  857. bool EmittedProtocolRef = false;
  858. /// A flag indicating if we've emitted at least one class.
  859. /// If we haven't, then we need to emit an empty protocol, to ensure that the
  860. /// __start__objc_classes and __stop__objc_classes sections / exist.
  861. bool EmittedClass = false;
  862. /// Generate the name of a symbol for a reference to a class. Accesses to
  863. /// classes should be indirected via this.
  864. std::string SymbolForClassRef(StringRef Name, bool isWeak) {
  865. if (isWeak)
  866. return (StringRef("._OBJC_WEAK_REF_CLASS_") + Name).str();
  867. else
  868. return (StringRef("._OBJC_REF_CLASS_") + Name).str();
  869. }
  870. /// Generate the name of a class symbol.
  871. std::string SymbolForClass(StringRef Name) {
  872. return (StringRef("._OBJC_CLASS_") + Name).str();
  873. }
  874. void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
  875. ArrayRef<llvm::Value*> Args) {
  876. SmallVector<llvm::Type *,8> Types;
  877. for (auto *Arg : Args)
  878. Types.push_back(Arg->getType());
  879. llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
  880. false);
  881. llvm::Value *Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
  882. B.CreateCall(Fn, Args);
  883. }
  884. ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
  885. auto Str = SL->getString();
  886. CharUnits Align = CGM.getPointerAlign();
  887. // Look for an existing one
  888. llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
  889. if (old != ObjCStrings.end())
  890. return ConstantAddress(old->getValue(), Align);
  891. bool isNonASCII = SL->containsNonAscii();
  892. auto LiteralLength = SL->getLength();
  893. if ((CGM.getTarget().getPointerWidth(0) == 64) &&
  894. (LiteralLength < 9) && !isNonASCII) {
  895. // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
  896. // ASCII characters in the high 56 bits, followed by a 4-bit length and a
  897. // 3-bit tag (which is always 4).
  898. uint64_t str = 0;
  899. // Fill in the characters
  900. for (unsigned i=0 ; i<LiteralLength ; i++)
  901. str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
  902. // Fill in the length
  903. str |= LiteralLength << 3;
  904. // Set the tag
  905. str |= 4;
  906. auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
  907. llvm::ConstantInt::get(Int64Ty, str), IdTy);
  908. ObjCStrings[Str] = ObjCStr;
  909. return ConstantAddress(ObjCStr, Align);
  910. }
  911. StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
  912. if (StringClass.empty()) StringClass = "NSConstantString";
  913. std::string Sym = SymbolForClass(StringClass);
  914. llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
  915. if (!isa)
  916. isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
  917. llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
  918. else if (isa->getType() != PtrToIdTy)
  919. isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
  920. // struct
  921. // {
  922. // Class isa;
  923. // uint32_t flags;
  924. // uint32_t length; // Number of codepoints
  925. // uint32_t size; // Number of bytes
  926. // uint32_t hash;
  927. // const char *data;
  928. // };
  929. ConstantInitBuilder Builder(CGM);
  930. auto Fields = Builder.beginStruct();
  931. Fields.add(isa);
  932. // For now, all non-ASCII strings are represented as UTF-16. As such, the
  933. // number of bytes is simply double the number of UTF-16 codepoints. In
  934. // ASCII strings, the number of bytes is equal to the number of non-ASCII
  935. // codepoints.
  936. if (isNonASCII) {
  937. unsigned NumU8CodeUnits = Str.size();
  938. // A UTF-16 representation of a unicode string contains at most the same
  939. // number of code units as a UTF-8 representation. Allocate that much
  940. // space, plus one for the final null character.
  941. SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
  942. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
  943. llvm::UTF16 *ToPtr = &ToBuf[0];
  944. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
  945. &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
  946. uint32_t StringLength = ToPtr - &ToBuf[0];
  947. // Add null terminator
  948. *ToPtr = 0;
  949. // Flags: 2 indicates UTF-16 encoding
  950. Fields.addInt(Int32Ty, 2);
  951. // Number of UTF-16 codepoints
  952. Fields.addInt(Int32Ty, StringLength);
  953. // Number of bytes
  954. Fields.addInt(Int32Ty, StringLength * 2);
  955. // Hash. Not currently initialised by the compiler.
  956. Fields.addInt(Int32Ty, 0);
  957. // pointer to the data string.
  958. auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
  959. auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
  960. auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
  961. /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
  962. Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  963. Fields.add(Buffer);
  964. } else {
  965. // Flags: 0 indicates ASCII encoding
  966. Fields.addInt(Int32Ty, 0);
  967. // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
  968. Fields.addInt(Int32Ty, Str.size());
  969. // Number of bytes
  970. Fields.addInt(Int32Ty, Str.size());
  971. // Hash. Not currently initialised by the compiler.
  972. Fields.addInt(Int32Ty, 0);
  973. // Data pointer
  974. Fields.add(MakeConstantString(Str));
  975. }
  976. std::string StringName;
  977. bool isNamed = !isNonASCII;
  978. if (isNamed) {
  979. StringName = ".objc_str_";
  980. for (int i=0,e=Str.size() ; i<e ; ++i) {
  981. unsigned char c = Str[i];
  982. if (isalnum(c))
  983. StringName += c;
  984. else if (c == ' ')
  985. StringName += '_';
  986. else {
  987. isNamed = false;
  988. break;
  989. }
  990. }
  991. }
  992. auto *ObjCStrGV =
  993. Fields.finishAndCreateGlobal(
  994. isNamed ? StringRef(StringName) : ".objc_string",
  995. Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
  996. : llvm::GlobalValue::PrivateLinkage);
  997. ObjCStrGV->setSection(sectionName<ConstantStringSection>());
  998. if (isNamed) {
  999. ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
  1000. ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1001. }
  1002. llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
  1003. ObjCStrings[Str] = ObjCStr;
  1004. ConstantStrings.push_back(ObjCStr);
  1005. return ConstantAddress(ObjCStr, Align);
  1006. }
  1007. void PushProperty(ConstantArrayBuilder &PropertiesArray,
  1008. const ObjCPropertyDecl *property,
  1009. const Decl *OCD,
  1010. bool isSynthesized=true, bool
  1011. isDynamic=true) override {
  1012. // struct objc_property
  1013. // {
  1014. // const char *name;
  1015. // const char *attributes;
  1016. // const char *type;
  1017. // SEL getter;
  1018. // SEL setter;
  1019. // };
  1020. auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
  1021. ASTContext &Context = CGM.getContext();
  1022. Fields.add(MakeConstantString(property->getNameAsString()));
  1023. std::string TypeStr =
  1024. CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
  1025. Fields.add(MakeConstantString(TypeStr));
  1026. std::string typeStr;
  1027. Context.getObjCEncodingForType(property->getType(), typeStr);
  1028. Fields.add(MakeConstantString(typeStr));
  1029. auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
  1030. if (accessor) {
  1031. std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
  1032. Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
  1033. } else {
  1034. Fields.add(NULLPtr);
  1035. }
  1036. };
  1037. addPropertyMethod(property->getGetterMethodDecl());
  1038. addPropertyMethod(property->getSetterMethodDecl());
  1039. Fields.finishAndAddTo(PropertiesArray);
  1040. }
  1041. llvm::Constant *
  1042. GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
  1043. // struct objc_protocol_method_description
  1044. // {
  1045. // SEL selector;
  1046. // const char *types;
  1047. // };
  1048. llvm::StructType *ObjCMethodDescTy =
  1049. llvm::StructType::get(CGM.getLLVMContext(),
  1050. { PtrToInt8Ty, PtrToInt8Ty });
  1051. ASTContext &Context = CGM.getContext();
  1052. ConstantInitBuilder Builder(CGM);
  1053. // struct objc_protocol_method_description_list
  1054. // {
  1055. // int count;
  1056. // int size;
  1057. // struct objc_protocol_method_description methods[];
  1058. // };
  1059. auto MethodList = Builder.beginStruct();
  1060. // int count;
  1061. MethodList.addInt(IntTy, Methods.size());
  1062. // int size; // sizeof(struct objc_method_description)
  1063. llvm::DataLayout td(&TheModule);
  1064. MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
  1065. CGM.getContext().getCharWidth());
  1066. // struct objc_method_description[]
  1067. auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
  1068. for (auto *M : Methods) {
  1069. auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
  1070. Method.add(CGObjCGNU::GetConstantSelector(M));
  1071. Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
  1072. Method.finishAndAddTo(MethodArray);
  1073. }
  1074. MethodArray.finishAndAddTo(MethodList);
  1075. return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
  1076. CGM.getPointerAlign());
  1077. }
  1078. llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
  1079. override {
  1080. SmallVector<llvm::Constant*, 16> Protocols;
  1081. for (const auto *PI : OCD->getReferencedProtocols())
  1082. Protocols.push_back(
  1083. llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
  1084. ProtocolPtrTy));
  1085. return GenerateProtocolList(Protocols);
  1086. }
  1087. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  1088. llvm::Value *cmd, MessageSendInfo &MSI) override {
  1089. // Don't access the slot unless we're trying to cache the result.
  1090. CGBuilderTy &Builder = CGF.Builder;
  1091. llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
  1092. PtrToObjCSuperTy).getPointer(), cmd};
  1093. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
  1094. }
  1095. llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
  1096. std::string SymbolName = SymbolForClassRef(Name, isWeak);
  1097. auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
  1098. if (ClassSymbol)
  1099. return ClassSymbol;
  1100. ClassSymbol = new llvm::GlobalVariable(TheModule,
  1101. IdTy, false, llvm::GlobalValue::ExternalLinkage,
  1102. nullptr, SymbolName);
  1103. // If this is a weak symbol, then we are creating a valid definition for
  1104. // the symbol, pointing to a weak definition of the real class pointer. If
  1105. // this is not a weak reference, then we are expecting another compilation
  1106. // unit to provide the real indirection symbol.
  1107. if (isWeak)
  1108. ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
  1109. Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
  1110. nullptr, SymbolForClass(Name)));
  1111. assert(ClassSymbol->getName() == SymbolName);
  1112. return ClassSymbol;
  1113. }
  1114. llvm::Value *GetClassNamed(CodeGenFunction &CGF,
  1115. const std::string &Name,
  1116. bool isWeak) override {
  1117. return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
  1118. CGM.getPointerAlign()));
  1119. }
  1120. int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
  1121. // typedef enum {
  1122. // ownership_invalid = 0,
  1123. // ownership_strong = 1,
  1124. // ownership_weak = 2,
  1125. // ownership_unsafe = 3
  1126. // } ivar_ownership;
  1127. int Flag;
  1128. switch (Ownership) {
  1129. case Qualifiers::OCL_Strong:
  1130. Flag = 1;
  1131. break;
  1132. case Qualifiers::OCL_Weak:
  1133. Flag = 2;
  1134. break;
  1135. case Qualifiers::OCL_ExplicitNone:
  1136. Flag = 3;
  1137. break;
  1138. case Qualifiers::OCL_None:
  1139. case Qualifiers::OCL_Autoreleasing:
  1140. assert(Ownership != Qualifiers::OCL_Autoreleasing);
  1141. Flag = 0;
  1142. }
  1143. return Flag;
  1144. }
  1145. llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
  1146. ArrayRef<llvm::Constant *> IvarTypes,
  1147. ArrayRef<llvm::Constant *> IvarOffsets,
  1148. ArrayRef<llvm::Constant *> IvarAlign,
  1149. ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
  1150. llvm_unreachable("Method should not be called!");
  1151. }
  1152. llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
  1153. std::string Name = SymbolForProtocol(ProtocolName);
  1154. auto *GV = TheModule.getGlobalVariable(Name);
  1155. if (!GV) {
  1156. // Emit a placeholder symbol.
  1157. GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
  1158. llvm::GlobalValue::ExternalLinkage, nullptr, Name);
  1159. GV->setAlignment(CGM.getPointerAlign().getQuantity());
  1160. }
  1161. return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
  1162. }
  1163. /// Existing protocol references.
  1164. llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
  1165. llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
  1166. const ObjCProtocolDecl *PD) override {
  1167. auto Name = PD->getNameAsString();
  1168. auto *&Ref = ExistingProtocolRefs[Name];
  1169. if (!Ref) {
  1170. auto *&Protocol = ExistingProtocols[Name];
  1171. if (!Protocol)
  1172. Protocol = GenerateProtocolRef(PD);
  1173. std::string RefName = SymbolForProtocolRef(Name);
  1174. assert(!TheModule.getGlobalVariable(RefName));
  1175. // Emit a reference symbol.
  1176. auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
  1177. false, llvm::GlobalValue::LinkOnceODRLinkage,
  1178. llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
  1179. GV->setComdat(TheModule.getOrInsertComdat(RefName));
  1180. GV->setSection(sectionName<ProtocolReferenceSection>());
  1181. GV->setAlignment(CGM.getPointerAlign().getQuantity());
  1182. Ref = GV;
  1183. }
  1184. EmittedProtocolRef = true;
  1185. return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
  1186. }
  1187. llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
  1188. llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
  1189. Protocols.size());
  1190. llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
  1191. Protocols);
  1192. ConstantInitBuilder builder(CGM);
  1193. auto ProtocolBuilder = builder.beginStruct();
  1194. ProtocolBuilder.addNullPointer(PtrTy);
  1195. ProtocolBuilder.addInt(SizeTy, Protocols.size());
  1196. ProtocolBuilder.add(ProtocolArray);
  1197. return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
  1198. CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
  1199. }
  1200. void GenerateProtocol(const ObjCProtocolDecl *PD) override {
  1201. // Do nothing - we only emit referenced protocols.
  1202. }
  1203. llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
  1204. std::string ProtocolName = PD->getNameAsString();
  1205. auto *&Protocol = ExistingProtocols[ProtocolName];
  1206. if (Protocol)
  1207. return Protocol;
  1208. EmittedProtocol = true;
  1209. auto SymName = SymbolForProtocol(ProtocolName);
  1210. auto *OldGV = TheModule.getGlobalVariable(SymName);
  1211. // Use the protocol definition, if there is one.
  1212. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  1213. PD = Def;
  1214. else {
  1215. // If there is no definition, then create an external linkage symbol and
  1216. // hope that someone else fills it in for us (and fail to link if they
  1217. // don't).
  1218. assert(!OldGV);
  1219. Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
  1220. /*isConstant*/false,
  1221. llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
  1222. return Protocol;
  1223. }
  1224. SmallVector<llvm::Constant*, 16> Protocols;
  1225. for (const auto *PI : PD->protocols())
  1226. Protocols.push_back(
  1227. llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
  1228. ProtocolPtrTy));
  1229. llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
  1230. // Collect information about methods
  1231. llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
  1232. llvm::Constant *ClassMethodList, *OptionalClassMethodList;
  1233. EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
  1234. OptionalInstanceMethodList);
  1235. EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
  1236. OptionalClassMethodList);
  1237. // The isa pointer must be set to a magic number so the runtime knows it's
  1238. // the correct layout.
  1239. ConstantInitBuilder builder(CGM);
  1240. auto ProtocolBuilder = builder.beginStruct();
  1241. ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
  1242. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  1243. ProtocolBuilder.add(MakeConstantString(ProtocolName));
  1244. ProtocolBuilder.add(ProtocolList);
  1245. ProtocolBuilder.add(InstanceMethodList);
  1246. ProtocolBuilder.add(ClassMethodList);
  1247. ProtocolBuilder.add(OptionalInstanceMethodList);
  1248. ProtocolBuilder.add(OptionalClassMethodList);
  1249. // Required instance properties
  1250. ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
  1251. // Optional instance properties
  1252. ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
  1253. // Required class properties
  1254. ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
  1255. // Optional class properties
  1256. ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
  1257. auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
  1258. CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
  1259. GV->setSection(sectionName<ProtocolSection>());
  1260. GV->setComdat(TheModule.getOrInsertComdat(SymName));
  1261. if (OldGV) {
  1262. OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
  1263. OldGV->getType()));
  1264. OldGV->removeFromParent();
  1265. GV->setName(SymName);
  1266. }
  1267. Protocol = GV;
  1268. return GV;
  1269. }
  1270. llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
  1271. if (Val->getType() == Ty)
  1272. return Val;
  1273. return llvm::ConstantExpr::getBitCast(Val, Ty);
  1274. }
  1275. llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
  1276. const std::string &TypeEncoding) override {
  1277. return GetConstantSelector(Sel, TypeEncoding);
  1278. }
  1279. llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
  1280. if (TypeEncoding.empty())
  1281. return NULLPtr;
  1282. std::string MangledTypes = TypeEncoding;
  1283. std::replace(MangledTypes.begin(), MangledTypes.end(),
  1284. '@', '\1');
  1285. std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
  1286. auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
  1287. if (!TypesGlobal) {
  1288. llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
  1289. TypeEncoding);
  1290. auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
  1291. true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
  1292. GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
  1293. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1294. TypesGlobal = GV;
  1295. }
  1296. return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
  1297. TypesGlobal, Zeros);
  1298. }
  1299. llvm::Constant *GetConstantSelector(Selector Sel,
  1300. const std::string &TypeEncoding) override {
  1301. // @ is used as a special character in symbol names (used for symbol
  1302. // versioning), so mangle the name to not include it. Replace it with a
  1303. // character that is not a valid type encoding character (and, being
  1304. // non-printable, never will be!)
  1305. std::string MangledTypes = TypeEncoding;
  1306. std::replace(MangledTypes.begin(), MangledTypes.end(),
  1307. '@', '\1');
  1308. auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
  1309. MangledTypes).str();
  1310. if (auto *GV = TheModule.getNamedGlobal(SelVarName))
  1311. return EnforceType(GV, SelectorTy);
  1312. ConstantInitBuilder builder(CGM);
  1313. auto SelBuilder = builder.beginStruct();
  1314. SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
  1315. true));
  1316. SelBuilder.add(GetTypeString(TypeEncoding));
  1317. auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
  1318. CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
  1319. GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
  1320. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1321. GV->setSection(sectionName<SelectorSection>());
  1322. auto *SelVal = EnforceType(GV, SelectorTy);
  1323. return SelVal;
  1324. }
  1325. llvm::StructType *emptyStruct = nullptr;
  1326. /// Return pointers to the start and end of a section. On ELF platforms, we
  1327. /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
  1328. /// to the start and end of section names, as long as those section names are
  1329. /// valid identifiers and the symbols are referenced but not defined. On
  1330. /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
  1331. /// by subsections and place everything that we want to reference in a middle
  1332. /// subsection and then insert zero-sized symbols in subsections a and z.
  1333. std::pair<llvm::Constant*,llvm::Constant*>
  1334. GetSectionBounds(StringRef Section) {
  1335. if (CGM.getTriple().isOSBinFormatCOFF()) {
  1336. if (emptyStruct == nullptr) {
  1337. emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
  1338. emptyStruct->setBody({}, /*isPacked*/true);
  1339. }
  1340. auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
  1341. auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
  1342. auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
  1343. /*isConstant*/false,
  1344. llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
  1345. Section);
  1346. Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1347. Sym->setSection((Section + SecSuffix).str());
  1348. Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
  1349. Section).str()));
  1350. Sym->setAlignment(1);
  1351. return Sym;
  1352. };
  1353. return { Sym("__start_", "$a"), Sym("__stop", "$z") };
  1354. }
  1355. auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
  1356. /*isConstant*/false,
  1357. llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
  1358. Section);
  1359. Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1360. auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
  1361. /*isConstant*/false,
  1362. llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
  1363. Section);
  1364. Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1365. return { Start, Stop };
  1366. }
  1367. CatchTypeInfo getCatchAllTypeInfo() override {
  1368. return CGM.getCXXABI().getCatchAllTypeInfo();
  1369. }
  1370. llvm::Function *ModuleInitFunction() override {
  1371. llvm::Function *LoadFunction = llvm::Function::Create(
  1372. llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
  1373. llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
  1374. &TheModule);
  1375. LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1376. LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
  1377. llvm::BasicBlock *EntryBB =
  1378. llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
  1379. CGBuilderTy B(CGM, VMContext);
  1380. B.SetInsertPoint(EntryBB);
  1381. ConstantInitBuilder builder(CGM);
  1382. auto InitStructBuilder = builder.beginStruct();
  1383. InitStructBuilder.addInt(Int64Ty, 0);
  1384. for (auto *s : SectionsBaseNames) {
  1385. auto bounds = GetSectionBounds(s);
  1386. InitStructBuilder.add(bounds.first);
  1387. InitStructBuilder.add(bounds.second);
  1388. };
  1389. auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
  1390. CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
  1391. InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1392. InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
  1393. CallRuntimeFunction(B, "__objc_load", {InitStruct});;
  1394. B.CreateRetVoid();
  1395. // Make sure that the optimisers don't delete this function.
  1396. CGM.addCompilerUsedGlobal(LoadFunction);
  1397. // FIXME: Currently ELF only!
  1398. // We have to do this by hand, rather than with @llvm.ctors, so that the
  1399. // linker can remove the duplicate invocations.
  1400. auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
  1401. /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
  1402. LoadFunction, ".objc_ctor");
  1403. // Check that this hasn't been renamed. This shouldn't happen, because
  1404. // this function should be called precisely once.
  1405. assert(InitVar->getName() == ".objc_ctor");
  1406. // In Windows, initialisers are sorted by the suffix. XCL is for library
  1407. // initialisers, which run before user initialisers. We are running
  1408. // Objective-C loads at the end of library load. This means +load methods
  1409. // will run before any other static constructors, but that static
  1410. // constructors can see a fully initialised Objective-C state.
  1411. if (CGM.getTriple().isOSBinFormatCOFF())
  1412. InitVar->setSection(".CRT$XCLz");
  1413. else
  1414. InitVar->setSection(".ctors");
  1415. InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1416. InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
  1417. CGM.addUsedGlobal(InitVar);
  1418. for (auto *C : Categories) {
  1419. auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
  1420. Cat->setSection(sectionName<CategorySection>());
  1421. CGM.addUsedGlobal(Cat);
  1422. }
  1423. auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
  1424. StringRef Section) {
  1425. auto nullBuilder = builder.beginStruct();
  1426. for (auto *F : Init)
  1427. nullBuilder.add(F);
  1428. auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
  1429. false, llvm::GlobalValue::LinkOnceODRLinkage);
  1430. GV->setSection(Section);
  1431. GV->setComdat(TheModule.getOrInsertComdat(Name));
  1432. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  1433. CGM.addUsedGlobal(GV);
  1434. return GV;
  1435. };
  1436. for (auto clsAlias : ClassAliases)
  1437. createNullGlobal(std::string(".objc_class_alias") +
  1438. clsAlias.second, { MakeConstantString(clsAlias.second),
  1439. GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
  1440. // On ELF platforms, add a null value for each special section so that we
  1441. // can always guarantee that the _start and _stop symbols will exist and be
  1442. // meaningful. This is not required on COFF platforms, where our start and
  1443. // stop symbols will create the section.
  1444. if (!CGM.getTriple().isOSBinFormatCOFF()) {
  1445. createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
  1446. sectionName<SelectorSection>());
  1447. if (Categories.empty())
  1448. createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
  1449. NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
  1450. sectionName<CategorySection>());
  1451. if (!EmittedClass) {
  1452. createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
  1453. sectionName<ClassSection>());
  1454. createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
  1455. sectionName<ClassReferenceSection>());
  1456. }
  1457. if (!EmittedProtocol)
  1458. createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
  1459. NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
  1460. NULLPtr}, sectionName<ProtocolSection>());
  1461. if (!EmittedProtocolRef)
  1462. createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
  1463. sectionName<ProtocolReferenceSection>());
  1464. if (ClassAliases.empty())
  1465. createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
  1466. sectionName<ClassAliasSection>());
  1467. if (ConstantStrings.empty()) {
  1468. auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
  1469. createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
  1470. i32Zero, i32Zero, i32Zero, NULLPtr },
  1471. sectionName<ConstantStringSection>());
  1472. }
  1473. }
  1474. ConstantStrings.clear();
  1475. Categories.clear();
  1476. Classes.clear();
  1477. return nullptr;
  1478. }
  1479. /// In the v2 ABI, ivar offset variables use the type encoding in their name
  1480. /// to trigger linker failures if the types don't match.
  1481. std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
  1482. const ObjCIvarDecl *Ivar) override {
  1483. std::string TypeEncoding;
  1484. CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
  1485. // Prevent the @ from being interpreted as a symbol version.
  1486. std::replace(TypeEncoding.begin(), TypeEncoding.end(),
  1487. '@', '\1');
  1488. const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
  1489. + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
  1490. return Name;
  1491. }
  1492. llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
  1493. const ObjCInterfaceDecl *Interface,
  1494. const ObjCIvarDecl *Ivar) override {
  1495. const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
  1496. llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
  1497. if (!IvarOffsetPointer)
  1498. IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
  1499. llvm::GlobalValue::ExternalLinkage, nullptr, Name);
  1500. CharUnits Align = CGM.getIntAlign();
  1501. llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
  1502. if (Offset->getType() != PtrDiffTy)
  1503. Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
  1504. return Offset;
  1505. }
  1506. void GenerateClass(const ObjCImplementationDecl *OID) override {
  1507. ASTContext &Context = CGM.getContext();
  1508. // Get the class name
  1509. ObjCInterfaceDecl *classDecl =
  1510. const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
  1511. std::string className = classDecl->getNameAsString();
  1512. auto *classNameConstant = MakeConstantString(className);
  1513. ConstantInitBuilder builder(CGM);
  1514. auto metaclassFields = builder.beginStruct();
  1515. // struct objc_class *isa;
  1516. metaclassFields.addNullPointer(PtrTy);
  1517. // struct objc_class *super_class;
  1518. metaclassFields.addNullPointer(PtrTy);
  1519. // const char *name;
  1520. metaclassFields.add(classNameConstant);
  1521. // long version;
  1522. metaclassFields.addInt(LongTy, 0);
  1523. // unsigned long info;
  1524. // objc_class_flag_meta
  1525. metaclassFields.addInt(LongTy, 1);
  1526. // long instance_size;
  1527. // Setting this to zero is consistent with the older ABI, but it might be
  1528. // more sensible to set this to sizeof(struct objc_class)
  1529. metaclassFields.addInt(LongTy, 0);
  1530. // struct objc_ivar_list *ivars;
  1531. metaclassFields.addNullPointer(PtrTy);
  1532. // struct objc_method_list *methods
  1533. // FIXME: Almost identical code is copied and pasted below for the
  1534. // class, but refactoring it cleanly requires C++14 generic lambdas.
  1535. if (OID->classmeth_begin() == OID->classmeth_end())
  1536. metaclassFields.addNullPointer(PtrTy);
  1537. else {
  1538. SmallVector<ObjCMethodDecl*, 16> ClassMethods;
  1539. ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
  1540. OID->classmeth_end());
  1541. metaclassFields.addBitCast(
  1542. GenerateMethodList(className, "", ClassMethods, true),
  1543. PtrTy);
  1544. }
  1545. // void *dtable;
  1546. metaclassFields.addNullPointer(PtrTy);
  1547. // IMP cxx_construct;
  1548. metaclassFields.addNullPointer(PtrTy);
  1549. // IMP cxx_destruct;
  1550. metaclassFields.addNullPointer(PtrTy);
  1551. // struct objc_class *subclass_list
  1552. metaclassFields.addNullPointer(PtrTy);
  1553. // struct objc_class *sibling_class
  1554. metaclassFields.addNullPointer(PtrTy);
  1555. // struct objc_protocol_list *protocols;
  1556. metaclassFields.addNullPointer(PtrTy);
  1557. // struct reference_list *extra_data;
  1558. metaclassFields.addNullPointer(PtrTy);
  1559. // long abi_version;
  1560. metaclassFields.addInt(LongTy, 0);
  1561. // struct objc_property_list *properties
  1562. metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
  1563. auto *metaclass = metaclassFields.finishAndCreateGlobal("._OBJC_METACLASS_"
  1564. + className, CGM.getPointerAlign());
  1565. auto classFields = builder.beginStruct();
  1566. // struct objc_class *isa;
  1567. classFields.add(metaclass);
  1568. // struct objc_class *super_class;
  1569. // Get the superclass name.
  1570. const ObjCInterfaceDecl * SuperClassDecl =
  1571. OID->getClassInterface()->getSuperClass();
  1572. if (SuperClassDecl) {
  1573. auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
  1574. llvm::Constant *SuperClass = TheModule.getNamedGlobal(SuperClassName);
  1575. if (!SuperClass)
  1576. {
  1577. SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
  1578. llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
  1579. }
  1580. classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
  1581. } else
  1582. classFields.addNullPointer(PtrTy);
  1583. // const char *name;
  1584. classFields.add(classNameConstant);
  1585. // long version;
  1586. classFields.addInt(LongTy, 0);
  1587. // unsigned long info;
  1588. // !objc_class_flag_meta
  1589. classFields.addInt(LongTy, 0);
  1590. // long instance_size;
  1591. int superInstanceSize = !SuperClassDecl ? 0 :
  1592. Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
  1593. // Instance size is negative for classes that have not yet had their ivar
  1594. // layout calculated.
  1595. classFields.addInt(LongTy,
  1596. 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
  1597. superInstanceSize));
  1598. if (classDecl->all_declared_ivar_begin() == nullptr)
  1599. classFields.addNullPointer(PtrTy);
  1600. else {
  1601. int ivar_count = 0;
  1602. for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
  1603. IVD = IVD->getNextIvar()) ivar_count++;
  1604. llvm::DataLayout td(&TheModule);
  1605. // struct objc_ivar_list *ivars;
  1606. ConstantInitBuilder b(CGM);
  1607. auto ivarListBuilder = b.beginStruct();
  1608. // int count;
  1609. ivarListBuilder.addInt(IntTy, ivar_count);
  1610. // size_t size;
  1611. llvm::StructType *ObjCIvarTy = llvm::StructType::get(
  1612. PtrToInt8Ty,
  1613. PtrToInt8Ty,
  1614. PtrToInt8Ty,
  1615. Int32Ty,
  1616. Int32Ty);
  1617. ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
  1618. CGM.getContext().getCharWidth());
  1619. // struct objc_ivar ivars[]
  1620. auto ivarArrayBuilder = ivarListBuilder.beginArray();
  1621. for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
  1622. IVD = IVD->getNextIvar()) {
  1623. auto ivarTy = IVD->getType();
  1624. auto ivarBuilder = ivarArrayBuilder.beginStruct();
  1625. // const char *name;
  1626. ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
  1627. // const char *type;
  1628. std::string TypeStr;
  1629. //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
  1630. Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
  1631. ivarBuilder.add(MakeConstantString(TypeStr));
  1632. // int *offset;
  1633. uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
  1634. uint64_t Offset = BaseOffset - superInstanceSize;
  1635. llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
  1636. std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
  1637. llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
  1638. if (OffsetVar)
  1639. OffsetVar->setInitializer(OffsetValue);
  1640. else
  1641. OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
  1642. false, llvm::GlobalValue::ExternalLinkage,
  1643. OffsetValue, OffsetName);
  1644. auto ivarVisibility =
  1645. (IVD->getAccessControl() == ObjCIvarDecl::Private ||
  1646. IVD->getAccessControl() == ObjCIvarDecl::Package ||
  1647. classDecl->getVisibility() == HiddenVisibility) ?
  1648. llvm::GlobalValue::HiddenVisibility :
  1649. llvm::GlobalValue::DefaultVisibility;
  1650. OffsetVar->setVisibility(ivarVisibility);
  1651. ivarBuilder.add(OffsetVar);
  1652. // Ivar size
  1653. ivarBuilder.addInt(Int32Ty,
  1654. CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
  1655. // Alignment will be stored as a base-2 log of the alignment.
  1656. int align = llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
  1657. // Objects that require more than 2^64-byte alignment should be impossible!
  1658. assert(align < 64);
  1659. // uint32_t flags;
  1660. // Bits 0-1 are ownership.
  1661. // Bit 2 indicates an extended type encoding
  1662. // Bits 3-8 contain log2(aligment)
  1663. ivarBuilder.addInt(Int32Ty,
  1664. (align << 3) | (1<<2) |
  1665. FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
  1666. ivarBuilder.finishAndAddTo(ivarArrayBuilder);
  1667. }
  1668. ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
  1669. auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
  1670. CGM.getPointerAlign(), /*constant*/ false,
  1671. llvm::GlobalValue::PrivateLinkage);
  1672. classFields.add(ivarList);
  1673. }
  1674. // struct objc_method_list *methods
  1675. SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
  1676. InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
  1677. OID->instmeth_end());
  1678. for (auto *propImpl : OID->property_impls())
  1679. if (propImpl->getPropertyImplementation() ==
  1680. ObjCPropertyImplDecl::Synthesize) {
  1681. ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
  1682. auto addIfExists = [&](const ObjCMethodDecl* OMD) {
  1683. if (OMD)
  1684. InstanceMethods.push_back(OMD);
  1685. };
  1686. addIfExists(prop->getGetterMethodDecl());
  1687. addIfExists(prop->getSetterMethodDecl());
  1688. }
  1689. if (InstanceMethods.size() == 0)
  1690. classFields.addNullPointer(PtrTy);
  1691. else
  1692. classFields.addBitCast(
  1693. GenerateMethodList(className, "", InstanceMethods, false),
  1694. PtrTy);
  1695. // void *dtable;
  1696. classFields.addNullPointer(PtrTy);
  1697. // IMP cxx_construct;
  1698. classFields.addNullPointer(PtrTy);
  1699. // IMP cxx_destruct;
  1700. classFields.addNullPointer(PtrTy);
  1701. // struct objc_class *subclass_list
  1702. classFields.addNullPointer(PtrTy);
  1703. // struct objc_class *sibling_class
  1704. classFields.addNullPointer(PtrTy);
  1705. // struct objc_protocol_list *protocols;
  1706. SmallVector<llvm::Constant*, 16> Protocols;
  1707. for (const auto *I : classDecl->protocols())
  1708. Protocols.push_back(
  1709. llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
  1710. ProtocolPtrTy));
  1711. if (Protocols.empty())
  1712. classFields.addNullPointer(PtrTy);
  1713. else
  1714. classFields.add(GenerateProtocolList(Protocols));
  1715. // struct reference_list *extra_data;
  1716. classFields.addNullPointer(PtrTy);
  1717. // long abi_version;
  1718. classFields.addInt(LongTy, 0);
  1719. // struct objc_property_list *properties
  1720. classFields.add(GeneratePropertyList(OID, classDecl));
  1721. auto *classStruct =
  1722. classFields.finishAndCreateGlobal(SymbolForClass(className),
  1723. CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
  1724. if (CGM.getTriple().isOSBinFormatCOFF()) {
  1725. auto Storage = llvm::GlobalValue::DefaultStorageClass;
  1726. if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
  1727. Storage = llvm::GlobalValue::DLLImportStorageClass;
  1728. else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
  1729. Storage = llvm::GlobalValue::DLLExportStorageClass;
  1730. cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(Storage);
  1731. }
  1732. auto *classRefSymbol = GetClassVar(className);
  1733. classRefSymbol->setSection(sectionName<ClassReferenceSection>());
  1734. classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
  1735. // Resolve the class aliases, if they exist.
  1736. // FIXME: Class pointer aliases shouldn't exist!
  1737. if (ClassPtrAlias) {
  1738. ClassPtrAlias->replaceAllUsesWith(
  1739. llvm::ConstantExpr::getBitCast(classStruct, IdTy));
  1740. ClassPtrAlias->eraseFromParent();
  1741. ClassPtrAlias = nullptr;
  1742. }
  1743. if (auto Placeholder =
  1744. TheModule.getNamedGlobal(SymbolForClass(className)))
  1745. if (Placeholder != classStruct) {
  1746. Placeholder->replaceAllUsesWith(
  1747. llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
  1748. Placeholder->eraseFromParent();
  1749. classStruct->setName(SymbolForClass(className));
  1750. }
  1751. if (MetaClassPtrAlias) {
  1752. MetaClassPtrAlias->replaceAllUsesWith(
  1753. llvm::ConstantExpr::getBitCast(metaclass, IdTy));
  1754. MetaClassPtrAlias->eraseFromParent();
  1755. MetaClassPtrAlias = nullptr;
  1756. }
  1757. assert(classStruct->getName() == SymbolForClass(className));
  1758. auto classInitRef = new llvm::GlobalVariable(TheModule,
  1759. classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
  1760. classStruct, "._OBJC_INIT_CLASS_" + className);
  1761. classInitRef->setSection(sectionName<ClassSection>());
  1762. CGM.addUsedGlobal(classInitRef);
  1763. EmittedClass = true;
  1764. }
  1765. public:
  1766. CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
  1767. MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
  1768. PtrToObjCSuperTy, SelectorTy);
  1769. // struct objc_property
  1770. // {
  1771. // const char *name;
  1772. // const char *attributes;
  1773. // const char *type;
  1774. // SEL getter;
  1775. // SEL setter;
  1776. // }
  1777. PropertyMetadataTy =
  1778. llvm::StructType::get(CGM.getLLVMContext(),
  1779. { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
  1780. }
  1781. };
  1782. const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
  1783. {
  1784. "__objc_selectors",
  1785. "__objc_classes",
  1786. "__objc_class_refs",
  1787. "__objc_cats",
  1788. "__objc_protocols",
  1789. "__objc_protocol_refs",
  1790. "__objc_class_aliases",
  1791. "__objc_constant_string"
  1792. };
  1793. /// Support for the ObjFW runtime.
  1794. class CGObjCObjFW: public CGObjCGNU {
  1795. protected:
  1796. /// The GCC ABI message lookup function. Returns an IMP pointing to the
  1797. /// method implementation for this message.
  1798. LazyRuntimeFunction MsgLookupFn;
  1799. /// stret lookup function. While this does not seem to make sense at the
  1800. /// first look, this is required to call the correct forwarding function.
  1801. LazyRuntimeFunction MsgLookupFnSRet;
  1802. /// The GCC ABI superclass message lookup function. Takes a pointer to a
  1803. /// structure describing the receiver and the class, and a selector as
  1804. /// arguments. Returns the IMP for the corresponding method.
  1805. LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
  1806. llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
  1807. llvm::Value *cmd, llvm::MDNode *node,
  1808. MessageSendInfo &MSI) override {
  1809. CGBuilderTy &Builder = CGF.Builder;
  1810. llvm::Value *args[] = {
  1811. EnforceType(Builder, Receiver, IdTy),
  1812. EnforceType(Builder, cmd, SelectorTy) };
  1813. llvm::CallBase *imp;
  1814. if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
  1815. imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
  1816. else
  1817. imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
  1818. imp->setMetadata(msgSendMDKind, node);
  1819. return imp;
  1820. }
  1821. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  1822. llvm::Value *cmd, MessageSendInfo &MSI) override {
  1823. CGBuilderTy &Builder = CGF.Builder;
  1824. llvm::Value *lookupArgs[] = {
  1825. EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
  1826. };
  1827. if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
  1828. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
  1829. else
  1830. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
  1831. }
  1832. llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
  1833. bool isWeak) override {
  1834. if (isWeak)
  1835. return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
  1836. EmitClassRef(Name);
  1837. std::string SymbolName = "_OBJC_CLASS_" + Name;
  1838. llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
  1839. if (!ClassSymbol)
  1840. ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
  1841. llvm::GlobalValue::ExternalLinkage,
  1842. nullptr, SymbolName);
  1843. return ClassSymbol;
  1844. }
  1845. public:
  1846. CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
  1847. // IMP objc_msg_lookup(id, SEL);
  1848. MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
  1849. MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
  1850. SelectorTy);
  1851. // IMP objc_msg_lookup_super(struct objc_super*, SEL);
  1852. MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
  1853. PtrToObjCSuperTy, SelectorTy);
  1854. MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
  1855. PtrToObjCSuperTy, SelectorTy);
  1856. }
  1857. };
  1858. } // end anonymous namespace
  1859. /// Emits a reference to a dummy variable which is emitted with each class.
  1860. /// This ensures that a linker error will be generated when trying to link
  1861. /// together modules where a referenced class is not defined.
  1862. void CGObjCGNU::EmitClassRef(const std::string &className) {
  1863. std::string symbolRef = "__objc_class_ref_" + className;
  1864. // Don't emit two copies of the same symbol
  1865. if (TheModule.getGlobalVariable(symbolRef))
  1866. return;
  1867. std::string symbolName = "__objc_class_name_" + className;
  1868. llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
  1869. if (!ClassSymbol) {
  1870. ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
  1871. llvm::GlobalValue::ExternalLinkage,
  1872. nullptr, symbolName);
  1873. }
  1874. new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
  1875. llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
  1876. }
  1877. CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
  1878. unsigned protocolClassVersion, unsigned classABI)
  1879. : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
  1880. VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
  1881. MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
  1882. ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
  1883. msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
  1884. usesSEHExceptions =
  1885. cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
  1886. CodeGenTypes &Types = CGM.getTypes();
  1887. IntTy = cast<llvm::IntegerType>(
  1888. Types.ConvertType(CGM.getContext().IntTy));
  1889. LongTy = cast<llvm::IntegerType>(
  1890. Types.ConvertType(CGM.getContext().LongTy));
  1891. SizeTy = cast<llvm::IntegerType>(
  1892. Types.ConvertType(CGM.getContext().getSizeType()));
  1893. PtrDiffTy = cast<llvm::IntegerType>(
  1894. Types.ConvertType(CGM.getContext().getPointerDiffType()));
  1895. BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
  1896. Int8Ty = llvm::Type::getInt8Ty(VMContext);
  1897. // C string type. Used in lots of places.
  1898. PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
  1899. ProtocolPtrTy = llvm::PointerType::getUnqual(
  1900. Types.ConvertType(CGM.getContext().getObjCProtoType()));
  1901. Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
  1902. Zeros[1] = Zeros[0];
  1903. NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
  1904. // Get the selector Type.
  1905. QualType selTy = CGM.getContext().getObjCSelType();
  1906. if (QualType() == selTy) {
  1907. SelectorTy = PtrToInt8Ty;
  1908. } else {
  1909. SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
  1910. }
  1911. PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
  1912. PtrTy = PtrToInt8Ty;
  1913. Int32Ty = llvm::Type::getInt32Ty(VMContext);
  1914. Int64Ty = llvm::Type::getInt64Ty(VMContext);
  1915. IntPtrTy =
  1916. CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
  1917. // Object type
  1918. QualType UnqualIdTy = CGM.getContext().getObjCIdType();
  1919. ASTIdTy = CanQualType();
  1920. if (UnqualIdTy != QualType()) {
  1921. ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
  1922. IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
  1923. } else {
  1924. IdTy = PtrToInt8Ty;
  1925. }
  1926. PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
  1927. ProtocolTy = llvm::StructType::get(IdTy,
  1928. PtrToInt8Ty, // name
  1929. PtrToInt8Ty, // protocols
  1930. PtrToInt8Ty, // instance methods
  1931. PtrToInt8Ty, // class methods
  1932. PtrToInt8Ty, // optional instance methods
  1933. PtrToInt8Ty, // optional class methods
  1934. PtrToInt8Ty, // properties
  1935. PtrToInt8Ty);// optional properties
  1936. // struct objc_property_gsv1
  1937. // {
  1938. // const char *name;
  1939. // char attributes;
  1940. // char attributes2;
  1941. // char unused1;
  1942. // char unused2;
  1943. // const char *getter_name;
  1944. // const char *getter_types;
  1945. // const char *setter_name;
  1946. // const char *setter_types;
  1947. // }
  1948. PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
  1949. PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
  1950. PtrToInt8Ty, PtrToInt8Ty });
  1951. ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
  1952. PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
  1953. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  1954. // void objc_exception_throw(id);
  1955. ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
  1956. ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
  1957. // int objc_sync_enter(id);
  1958. SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
  1959. // int objc_sync_exit(id);
  1960. SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
  1961. // void objc_enumerationMutation (id)
  1962. EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
  1963. // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
  1964. GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
  1965. PtrDiffTy, BoolTy);
  1966. // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
  1967. SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
  1968. PtrDiffTy, IdTy, BoolTy, BoolTy);
  1969. // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
  1970. GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
  1971. PtrDiffTy, BoolTy, BoolTy);
  1972. // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
  1973. SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
  1974. PtrDiffTy, BoolTy, BoolTy);
  1975. // IMP type
  1976. llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
  1977. IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
  1978. true));
  1979. const LangOptions &Opts = CGM.getLangOpts();
  1980. if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
  1981. RuntimeVersion = 10;
  1982. // Don't bother initialising the GC stuff unless we're compiling in GC mode
  1983. if (Opts.getGC() != LangOptions::NonGC) {
  1984. // This is a bit of an hack. We should sort this out by having a proper
  1985. // CGObjCGNUstep subclass for GC, but we may want to really support the old
  1986. // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
  1987. // Get selectors needed in GC mode
  1988. RetainSel = GetNullarySelector("retain", CGM.getContext());
  1989. ReleaseSel = GetNullarySelector("release", CGM.getContext());
  1990. AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
  1991. // Get functions needed in GC mode
  1992. // id objc_assign_ivar(id, id, ptrdiff_t);
  1993. IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
  1994. // id objc_assign_strongCast (id, id*)
  1995. StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
  1996. PtrToIdTy);
  1997. // id objc_assign_global(id, id*);
  1998. GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
  1999. // id objc_assign_weak(id, id*);
  2000. WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
  2001. // id objc_read_weak(id*);
  2002. WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
  2003. // void *objc_memmove_collectable(void*, void *, size_t);
  2004. MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
  2005. SizeTy);
  2006. }
  2007. }
  2008. llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
  2009. const std::string &Name, bool isWeak) {
  2010. llvm::Constant *ClassName = MakeConstantString(Name);
  2011. // With the incompatible ABI, this will need to be replaced with a direct
  2012. // reference to the class symbol. For the compatible nonfragile ABI we are
  2013. // still performing this lookup at run time but emitting the symbol for the
  2014. // class externally so that we can make the switch later.
  2015. //
  2016. // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
  2017. // with memoized versions or with static references if it's safe to do so.
  2018. if (!isWeak)
  2019. EmitClassRef(Name);
  2020. llvm::Constant *ClassLookupFn =
  2021. CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
  2022. "objc_lookup_class");
  2023. return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
  2024. }
  2025. // This has to perform the lookup every time, since posing and related
  2026. // techniques can modify the name -> class mapping.
  2027. llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
  2028. const ObjCInterfaceDecl *OID) {
  2029. auto *Value =
  2030. GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
  2031. if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
  2032. CGM.setGVProperties(ClassSymbol, OID);
  2033. return Value;
  2034. }
  2035. llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
  2036. auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
  2037. if (CGM.getTriple().isOSBinFormatCOFF()) {
  2038. if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
  2039. IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
  2040. TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
  2041. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2042. const VarDecl *VD = nullptr;
  2043. for (const auto &Result : DC->lookup(&II))
  2044. if ((VD = dyn_cast<VarDecl>(Result)))
  2045. break;
  2046. CGM.setGVProperties(ClassSymbol, VD);
  2047. }
  2048. }
  2049. return Value;
  2050. }
  2051. llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
  2052. const std::string &TypeEncoding) {
  2053. SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
  2054. llvm::GlobalAlias *SelValue = nullptr;
  2055. for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
  2056. e = Types.end() ; i!=e ; i++) {
  2057. if (i->first == TypeEncoding) {
  2058. SelValue = i->second;
  2059. break;
  2060. }
  2061. }
  2062. if (!SelValue) {
  2063. SelValue = llvm::GlobalAlias::create(
  2064. SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
  2065. ".objc_selector_" + Sel.getAsString(), &TheModule);
  2066. Types.emplace_back(TypeEncoding, SelValue);
  2067. }
  2068. return SelValue;
  2069. }
  2070. Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
  2071. llvm::Value *SelValue = GetSelector(CGF, Sel);
  2072. // Store it to a temporary. Does this satisfy the semantics of
  2073. // GetAddrOfSelector? Hopefully.
  2074. Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
  2075. CGF.getPointerAlign());
  2076. CGF.Builder.CreateStore(SelValue, tmp);
  2077. return tmp;
  2078. }
  2079. llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
  2080. return GetTypedSelector(CGF, Sel, std::string());
  2081. }
  2082. llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
  2083. const ObjCMethodDecl *Method) {
  2084. std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
  2085. return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
  2086. }
  2087. llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
  2088. if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
  2089. // With the old ABI, there was only one kind of catchall, which broke
  2090. // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
  2091. // a pointer indicating object catchalls, and NULL to indicate real
  2092. // catchalls
  2093. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  2094. return MakeConstantString("@id");
  2095. } else {
  2096. return nullptr;
  2097. }
  2098. }
  2099. // All other types should be Objective-C interface pointer types.
  2100. const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
  2101. assert(OPT && "Invalid @catch type.");
  2102. const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
  2103. assert(IDecl && "Invalid @catch type.");
  2104. return MakeConstantString(IDecl->getIdentifier()->getName());
  2105. }
  2106. llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
  2107. if (usesSEHExceptions)
  2108. return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
  2109. if (!CGM.getLangOpts().CPlusPlus)
  2110. return CGObjCGNU::GetEHType(T);
  2111. // For Objective-C++, we want to provide the ability to catch both C++ and
  2112. // Objective-C objects in the same function.
  2113. // There's a particular fixed type info for 'id'.
  2114. if (T->isObjCIdType() ||
  2115. T->isObjCQualifiedIdType()) {
  2116. llvm::Constant *IDEHType =
  2117. CGM.getModule().getGlobalVariable("__objc_id_type_info");
  2118. if (!IDEHType)
  2119. IDEHType =
  2120. new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
  2121. false,
  2122. llvm::GlobalValue::ExternalLinkage,
  2123. nullptr, "__objc_id_type_info");
  2124. return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
  2125. }
  2126. const ObjCObjectPointerType *PT =
  2127. T->getAs<ObjCObjectPointerType>();
  2128. assert(PT && "Invalid @catch type.");
  2129. const ObjCInterfaceType *IT = PT->getInterfaceType();
  2130. assert(IT && "Invalid @catch type.");
  2131. std::string className = IT->getDecl()->getIdentifier()->getName();
  2132. std::string typeinfoName = "__objc_eh_typeinfo_" + className;
  2133. // Return the existing typeinfo if it exists
  2134. llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
  2135. if (typeinfo)
  2136. return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
  2137. // Otherwise create it.
  2138. // vtable for gnustep::libobjc::__objc_class_type_info
  2139. // It's quite ugly hard-coding this. Ideally we'd generate it using the host
  2140. // platform's name mangling.
  2141. const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
  2142. auto *Vtable = TheModule.getGlobalVariable(vtableName);
  2143. if (!Vtable) {
  2144. Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
  2145. llvm::GlobalValue::ExternalLinkage,
  2146. nullptr, vtableName);
  2147. }
  2148. llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
  2149. auto *BVtable = llvm::ConstantExpr::getBitCast(
  2150. llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
  2151. PtrToInt8Ty);
  2152. llvm::Constant *typeName =
  2153. ExportUniqueString(className, "__objc_eh_typename_");
  2154. ConstantInitBuilder builder(CGM);
  2155. auto fields = builder.beginStruct();
  2156. fields.add(BVtable);
  2157. fields.add(typeName);
  2158. llvm::Constant *TI =
  2159. fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
  2160. CGM.getPointerAlign(),
  2161. /*constant*/ false,
  2162. llvm::GlobalValue::LinkOnceODRLinkage);
  2163. return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
  2164. }
  2165. /// Generate an NSConstantString object.
  2166. ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
  2167. std::string Str = SL->getString().str();
  2168. CharUnits Align = CGM.getPointerAlign();
  2169. // Look for an existing one
  2170. llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
  2171. if (old != ObjCStrings.end())
  2172. return ConstantAddress(old->getValue(), Align);
  2173. StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
  2174. if (StringClass.empty()) StringClass = "NSConstantString";
  2175. std::string Sym = "_OBJC_CLASS_";
  2176. Sym += StringClass;
  2177. llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
  2178. if (!isa)
  2179. isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
  2180. llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
  2181. else if (isa->getType() != PtrToIdTy)
  2182. isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
  2183. ConstantInitBuilder Builder(CGM);
  2184. auto Fields = Builder.beginStruct();
  2185. Fields.add(isa);
  2186. Fields.add(MakeConstantString(Str));
  2187. Fields.addInt(IntTy, Str.size());
  2188. llvm::Constant *ObjCStr =
  2189. Fields.finishAndCreateGlobal(".objc_str", Align);
  2190. ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
  2191. ObjCStrings[Str] = ObjCStr;
  2192. ConstantStrings.push_back(ObjCStr);
  2193. return ConstantAddress(ObjCStr, Align);
  2194. }
  2195. ///Generates a message send where the super is the receiver. This is a message
  2196. ///send to self with special delivery semantics indicating which class's method
  2197. ///should be called.
  2198. RValue
  2199. CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
  2200. ReturnValueSlot Return,
  2201. QualType ResultType,
  2202. Selector Sel,
  2203. const ObjCInterfaceDecl *Class,
  2204. bool isCategoryImpl,
  2205. llvm::Value *Receiver,
  2206. bool IsClassMessage,
  2207. const CallArgList &CallArgs,
  2208. const ObjCMethodDecl *Method) {
  2209. CGBuilderTy &Builder = CGF.Builder;
  2210. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
  2211. if (Sel == RetainSel || Sel == AutoreleaseSel) {
  2212. return RValue::get(EnforceType(Builder, Receiver,
  2213. CGM.getTypes().ConvertType(ResultType)));
  2214. }
  2215. if (Sel == ReleaseSel) {
  2216. return RValue::get(nullptr);
  2217. }
  2218. }
  2219. llvm::Value *cmd = GetSelector(CGF, Sel);
  2220. CallArgList ActualArgs;
  2221. ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
  2222. ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
  2223. ActualArgs.addFrom(CallArgs);
  2224. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  2225. llvm::Value *ReceiverClass = nullptr;
  2226. bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
  2227. if (isV2ABI) {
  2228. ReceiverClass = GetClassNamed(CGF,
  2229. Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
  2230. if (IsClassMessage) {
  2231. // Load the isa pointer of the superclass is this is a class method.
  2232. ReceiverClass = Builder.CreateBitCast(ReceiverClass,
  2233. llvm::PointerType::getUnqual(IdTy));
  2234. ReceiverClass =
  2235. Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
  2236. }
  2237. ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
  2238. } else {
  2239. if (isCategoryImpl) {
  2240. llvm::Constant *classLookupFunction = nullptr;
  2241. if (IsClassMessage) {
  2242. classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
  2243. IdTy, PtrTy, true), "objc_get_meta_class");
  2244. } else {
  2245. classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
  2246. IdTy, PtrTy, true), "objc_get_class");
  2247. }
  2248. ReceiverClass = Builder.CreateCall(classLookupFunction,
  2249. MakeConstantString(Class->getNameAsString()));
  2250. } else {
  2251. // Set up global aliases for the metaclass or class pointer if they do not
  2252. // already exist. These will are forward-references which will be set to
  2253. // pointers to the class and metaclass structure created for the runtime
  2254. // load function. To send a message to super, we look up the value of the
  2255. // super_class pointer from either the class or metaclass structure.
  2256. if (IsClassMessage) {
  2257. if (!MetaClassPtrAlias) {
  2258. MetaClassPtrAlias = llvm::GlobalAlias::create(
  2259. IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
  2260. ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
  2261. }
  2262. ReceiverClass = MetaClassPtrAlias;
  2263. } else {
  2264. if (!ClassPtrAlias) {
  2265. ClassPtrAlias = llvm::GlobalAlias::create(
  2266. IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
  2267. ".objc_class_ref" + Class->getNameAsString(), &TheModule);
  2268. }
  2269. ReceiverClass = ClassPtrAlias;
  2270. }
  2271. }
  2272. // Cast the pointer to a simplified version of the class structure
  2273. llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
  2274. ReceiverClass = Builder.CreateBitCast(ReceiverClass,
  2275. llvm::PointerType::getUnqual(CastTy));
  2276. // Get the superclass pointer
  2277. ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
  2278. // Load the superclass pointer
  2279. ReceiverClass =
  2280. Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
  2281. }
  2282. // Construct the structure used to look up the IMP
  2283. llvm::StructType *ObjCSuperTy =
  2284. llvm::StructType::get(Receiver->getType(), IdTy);
  2285. Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
  2286. CGF.getPointerAlign());
  2287. Builder.CreateStore(Receiver,
  2288. Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
  2289. Builder.CreateStore(ReceiverClass,
  2290. Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
  2291. ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
  2292. // Get the IMP
  2293. llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
  2294. imp = EnforceType(Builder, imp, MSI.MessengerType);
  2295. llvm::Metadata *impMD[] = {
  2296. llvm::MDString::get(VMContext, Sel.getAsString()),
  2297. llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
  2298. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  2299. llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
  2300. llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
  2301. CGCallee callee(CGCalleeInfo(), imp);
  2302. llvm::CallBase *call;
  2303. RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
  2304. call->setMetadata(msgSendMDKind, node);
  2305. return msgRet;
  2306. }
  2307. /// Generate code for a message send expression.
  2308. RValue
  2309. CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
  2310. ReturnValueSlot Return,
  2311. QualType ResultType,
  2312. Selector Sel,
  2313. llvm::Value *Receiver,
  2314. const CallArgList &CallArgs,
  2315. const ObjCInterfaceDecl *Class,
  2316. const ObjCMethodDecl *Method) {
  2317. CGBuilderTy &Builder = CGF.Builder;
  2318. // Strip out message sends to retain / release in GC mode
  2319. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
  2320. if (Sel == RetainSel || Sel == AutoreleaseSel) {
  2321. return RValue::get(EnforceType(Builder, Receiver,
  2322. CGM.getTypes().ConvertType(ResultType)));
  2323. }
  2324. if (Sel == ReleaseSel) {
  2325. return RValue::get(nullptr);
  2326. }
  2327. }
  2328. // If the return type is something that goes in an integer register, the
  2329. // runtime will handle 0 returns. For other cases, we fill in the 0 value
  2330. // ourselves.
  2331. //
  2332. // The language spec says the result of this kind of message send is
  2333. // undefined, but lots of people seem to have forgotten to read that
  2334. // paragraph and insist on sending messages to nil that have structure
  2335. // returns. With GCC, this generates a random return value (whatever happens
  2336. // to be on the stack / in those registers at the time) on most platforms,
  2337. // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
  2338. // the stack.
  2339. bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
  2340. ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
  2341. llvm::BasicBlock *startBB = nullptr;
  2342. llvm::BasicBlock *messageBB = nullptr;
  2343. llvm::BasicBlock *continueBB = nullptr;
  2344. if (!isPointerSizedReturn) {
  2345. startBB = Builder.GetInsertBlock();
  2346. messageBB = CGF.createBasicBlock("msgSend");
  2347. continueBB = CGF.createBasicBlock("continue");
  2348. llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
  2349. llvm::Constant::getNullValue(Receiver->getType()));
  2350. Builder.CreateCondBr(isNil, continueBB, messageBB);
  2351. CGF.EmitBlock(messageBB);
  2352. }
  2353. IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
  2354. llvm::Value *cmd;
  2355. if (Method)
  2356. cmd = GetSelector(CGF, Method);
  2357. else
  2358. cmd = GetSelector(CGF, Sel);
  2359. cmd = EnforceType(Builder, cmd, SelectorTy);
  2360. Receiver = EnforceType(Builder, Receiver, IdTy);
  2361. llvm::Metadata *impMD[] = {
  2362. llvm::MDString::get(VMContext, Sel.getAsString()),
  2363. llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
  2364. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  2365. llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
  2366. llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
  2367. CallArgList ActualArgs;
  2368. ActualArgs.add(RValue::get(Receiver), ASTIdTy);
  2369. ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
  2370. ActualArgs.addFrom(CallArgs);
  2371. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  2372. // Get the IMP to call
  2373. llvm::Value *imp;
  2374. // If we have non-legacy dispatch specified, we try using the objc_msgSend()
  2375. // functions. These are not supported on all platforms (or all runtimes on a
  2376. // given platform), so we
  2377. switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
  2378. case CodeGenOptions::Legacy:
  2379. imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
  2380. break;
  2381. case CodeGenOptions::Mixed:
  2382. case CodeGenOptions::NonLegacy:
  2383. if (CGM.ReturnTypeUsesFPRet(ResultType)) {
  2384. imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  2385. "objc_msgSend_fpret");
  2386. } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
  2387. // The actual types here don't matter - we're going to bitcast the
  2388. // function anyway
  2389. imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  2390. "objc_msgSend_stret");
  2391. } else {
  2392. imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  2393. "objc_msgSend");
  2394. }
  2395. }
  2396. // Reset the receiver in case the lookup modified it
  2397. ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
  2398. imp = EnforceType(Builder, imp, MSI.MessengerType);
  2399. llvm::CallBase *call;
  2400. CGCallee callee(CGCalleeInfo(), imp);
  2401. RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
  2402. call->setMetadata(msgSendMDKind, node);
  2403. if (!isPointerSizedReturn) {
  2404. messageBB = CGF.Builder.GetInsertBlock();
  2405. CGF.Builder.CreateBr(continueBB);
  2406. CGF.EmitBlock(continueBB);
  2407. if (msgRet.isScalar()) {
  2408. llvm::Value *v = msgRet.getScalarVal();
  2409. llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
  2410. phi->addIncoming(v, messageBB);
  2411. phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
  2412. msgRet = RValue::get(phi);
  2413. } else if (msgRet.isAggregate()) {
  2414. Address v = msgRet.getAggregateAddress();
  2415. llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
  2416. llvm::Type *RetTy = v.getElementType();
  2417. Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
  2418. CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
  2419. phi->addIncoming(v.getPointer(), messageBB);
  2420. phi->addIncoming(NullVal.getPointer(), startBB);
  2421. msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
  2422. } else /* isComplex() */ {
  2423. std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
  2424. llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
  2425. phi->addIncoming(v.first, messageBB);
  2426. phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
  2427. startBB);
  2428. llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
  2429. phi2->addIncoming(v.second, messageBB);
  2430. phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
  2431. startBB);
  2432. msgRet = RValue::getComplex(phi, phi2);
  2433. }
  2434. }
  2435. return msgRet;
  2436. }
  2437. /// Generates a MethodList. Used in construction of a objc_class and
  2438. /// objc_category structures.
  2439. llvm::Constant *CGObjCGNU::
  2440. GenerateMethodList(StringRef ClassName,
  2441. StringRef CategoryName,
  2442. ArrayRef<const ObjCMethodDecl*> Methods,
  2443. bool isClassMethodList) {
  2444. if (Methods.empty())
  2445. return NULLPtr;
  2446. ConstantInitBuilder Builder(CGM);
  2447. auto MethodList = Builder.beginStruct();
  2448. MethodList.addNullPointer(CGM.Int8PtrTy);
  2449. MethodList.addInt(Int32Ty, Methods.size());
  2450. // Get the method structure type.
  2451. llvm::StructType *ObjCMethodTy =
  2452. llvm::StructType::get(CGM.getLLVMContext(), {
  2453. PtrToInt8Ty, // Really a selector, but the runtime creates it us.
  2454. PtrToInt8Ty, // Method types
  2455. IMPTy // Method pointer
  2456. });
  2457. bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
  2458. if (isV2ABI) {
  2459. // size_t size;
  2460. llvm::DataLayout td(&TheModule);
  2461. MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
  2462. CGM.getContext().getCharWidth());
  2463. ObjCMethodTy =
  2464. llvm::StructType::get(CGM.getLLVMContext(), {
  2465. IMPTy, // Method pointer
  2466. PtrToInt8Ty, // Selector
  2467. PtrToInt8Ty // Extended type encoding
  2468. });
  2469. } else {
  2470. ObjCMethodTy =
  2471. llvm::StructType::get(CGM.getLLVMContext(), {
  2472. PtrToInt8Ty, // Really a selector, but the runtime creates it us.
  2473. PtrToInt8Ty, // Method types
  2474. IMPTy // Method pointer
  2475. });
  2476. }
  2477. auto MethodArray = MethodList.beginArray();
  2478. ASTContext &Context = CGM.getContext();
  2479. for (const auto *OMD : Methods) {
  2480. llvm::Constant *FnPtr =
  2481. TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
  2482. OMD->getSelector(),
  2483. isClassMethodList));
  2484. assert(FnPtr && "Can't generate metadata for method that doesn't exist");
  2485. auto Method = MethodArray.beginStruct(ObjCMethodTy);
  2486. if (isV2ABI) {
  2487. Method.addBitCast(FnPtr, IMPTy);
  2488. Method.add(GetConstantSelector(OMD->getSelector(),
  2489. Context.getObjCEncodingForMethodDecl(OMD)));
  2490. Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
  2491. } else {
  2492. Method.add(MakeConstantString(OMD->getSelector().getAsString()));
  2493. Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
  2494. Method.addBitCast(FnPtr, IMPTy);
  2495. }
  2496. Method.finishAndAddTo(MethodArray);
  2497. }
  2498. MethodArray.finishAndAddTo(MethodList);
  2499. // Create an instance of the structure
  2500. return MethodList.finishAndCreateGlobal(".objc_method_list",
  2501. CGM.getPointerAlign());
  2502. }
  2503. /// Generates an IvarList. Used in construction of a objc_class.
  2504. llvm::Constant *CGObjCGNU::
  2505. GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
  2506. ArrayRef<llvm::Constant *> IvarTypes,
  2507. ArrayRef<llvm::Constant *> IvarOffsets,
  2508. ArrayRef<llvm::Constant *> IvarAlign,
  2509. ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
  2510. if (IvarNames.empty())
  2511. return NULLPtr;
  2512. ConstantInitBuilder Builder(CGM);
  2513. // Structure containing array count followed by array.
  2514. auto IvarList = Builder.beginStruct();
  2515. IvarList.addInt(IntTy, (int)IvarNames.size());
  2516. // Get the ivar structure type.
  2517. llvm::StructType *ObjCIvarTy =
  2518. llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
  2519. // Array of ivar structures.
  2520. auto Ivars = IvarList.beginArray(ObjCIvarTy);
  2521. for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
  2522. auto Ivar = Ivars.beginStruct(ObjCIvarTy);
  2523. Ivar.add(IvarNames[i]);
  2524. Ivar.add(IvarTypes[i]);
  2525. Ivar.add(IvarOffsets[i]);
  2526. Ivar.finishAndAddTo(Ivars);
  2527. }
  2528. Ivars.finishAndAddTo(IvarList);
  2529. // Create an instance of the structure
  2530. return IvarList.finishAndCreateGlobal(".objc_ivar_list",
  2531. CGM.getPointerAlign());
  2532. }
  2533. /// Generate a class structure
  2534. llvm::Constant *CGObjCGNU::GenerateClassStructure(
  2535. llvm::Constant *MetaClass,
  2536. llvm::Constant *SuperClass,
  2537. unsigned info,
  2538. const char *Name,
  2539. llvm::Constant *Version,
  2540. llvm::Constant *InstanceSize,
  2541. llvm::Constant *IVars,
  2542. llvm::Constant *Methods,
  2543. llvm::Constant *Protocols,
  2544. llvm::Constant *IvarOffsets,
  2545. llvm::Constant *Properties,
  2546. llvm::Constant *StrongIvarBitmap,
  2547. llvm::Constant *WeakIvarBitmap,
  2548. bool isMeta) {
  2549. // Set up the class structure
  2550. // Note: Several of these are char*s when they should be ids. This is
  2551. // because the runtime performs this translation on load.
  2552. //
  2553. // Fields marked New ABI are part of the GNUstep runtime. We emit them
  2554. // anyway; the classes will still work with the GNU runtime, they will just
  2555. // be ignored.
  2556. llvm::StructType *ClassTy = llvm::StructType::get(
  2557. PtrToInt8Ty, // isa
  2558. PtrToInt8Ty, // super_class
  2559. PtrToInt8Ty, // name
  2560. LongTy, // version
  2561. LongTy, // info
  2562. LongTy, // instance_size
  2563. IVars->getType(), // ivars
  2564. Methods->getType(), // methods
  2565. // These are all filled in by the runtime, so we pretend
  2566. PtrTy, // dtable
  2567. PtrTy, // subclass_list
  2568. PtrTy, // sibling_class
  2569. PtrTy, // protocols
  2570. PtrTy, // gc_object_type
  2571. // New ABI:
  2572. LongTy, // abi_version
  2573. IvarOffsets->getType(), // ivar_offsets
  2574. Properties->getType(), // properties
  2575. IntPtrTy, // strong_pointers
  2576. IntPtrTy // weak_pointers
  2577. );
  2578. ConstantInitBuilder Builder(CGM);
  2579. auto Elements = Builder.beginStruct(ClassTy);
  2580. // Fill in the structure
  2581. // isa
  2582. Elements.addBitCast(MetaClass, PtrToInt8Ty);
  2583. // super_class
  2584. Elements.add(SuperClass);
  2585. // name
  2586. Elements.add(MakeConstantString(Name, ".class_name"));
  2587. // version
  2588. Elements.addInt(LongTy, 0);
  2589. // info
  2590. Elements.addInt(LongTy, info);
  2591. // instance_size
  2592. if (isMeta) {
  2593. llvm::DataLayout td(&TheModule);
  2594. Elements.addInt(LongTy,
  2595. td.getTypeSizeInBits(ClassTy) /
  2596. CGM.getContext().getCharWidth());
  2597. } else
  2598. Elements.add(InstanceSize);
  2599. // ivars
  2600. Elements.add(IVars);
  2601. // methods
  2602. Elements.add(Methods);
  2603. // These are all filled in by the runtime, so we pretend
  2604. // dtable
  2605. Elements.add(NULLPtr);
  2606. // subclass_list
  2607. Elements.add(NULLPtr);
  2608. // sibling_class
  2609. Elements.add(NULLPtr);
  2610. // protocols
  2611. Elements.addBitCast(Protocols, PtrTy);
  2612. // gc_object_type
  2613. Elements.add(NULLPtr);
  2614. // abi_version
  2615. Elements.addInt(LongTy, ClassABIVersion);
  2616. // ivar_offsets
  2617. Elements.add(IvarOffsets);
  2618. // properties
  2619. Elements.add(Properties);
  2620. // strong_pointers
  2621. Elements.add(StrongIvarBitmap);
  2622. // weak_pointers
  2623. Elements.add(WeakIvarBitmap);
  2624. // Create an instance of the structure
  2625. // This is now an externally visible symbol, so that we can speed up class
  2626. // messages in the next ABI. We may already have some weak references to
  2627. // this, so check and fix them properly.
  2628. std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
  2629. std::string(Name));
  2630. llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
  2631. llvm::Constant *Class =
  2632. Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
  2633. llvm::GlobalValue::ExternalLinkage);
  2634. if (ClassRef) {
  2635. ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
  2636. ClassRef->getType()));
  2637. ClassRef->removeFromParent();
  2638. Class->setName(ClassSym);
  2639. }
  2640. return Class;
  2641. }
  2642. llvm::Constant *CGObjCGNU::
  2643. GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
  2644. // Get the method structure type.
  2645. llvm::StructType *ObjCMethodDescTy =
  2646. llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
  2647. ASTContext &Context = CGM.getContext();
  2648. ConstantInitBuilder Builder(CGM);
  2649. auto MethodList = Builder.beginStruct();
  2650. MethodList.addInt(IntTy, Methods.size());
  2651. auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
  2652. for (auto *M : Methods) {
  2653. auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
  2654. Method.add(MakeConstantString(M->getSelector().getAsString()));
  2655. Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
  2656. Method.finishAndAddTo(MethodArray);
  2657. }
  2658. MethodArray.finishAndAddTo(MethodList);
  2659. return MethodList.finishAndCreateGlobal(".objc_method_list",
  2660. CGM.getPointerAlign());
  2661. }
  2662. // Create the protocol list structure used in classes, categories and so on
  2663. llvm::Constant *
  2664. CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
  2665. ConstantInitBuilder Builder(CGM);
  2666. auto ProtocolList = Builder.beginStruct();
  2667. ProtocolList.add(NULLPtr);
  2668. ProtocolList.addInt(LongTy, Protocols.size());
  2669. auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
  2670. for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
  2671. iter != endIter ; iter++) {
  2672. llvm::Constant *protocol = nullptr;
  2673. llvm::StringMap<llvm::Constant*>::iterator value =
  2674. ExistingProtocols.find(*iter);
  2675. if (value == ExistingProtocols.end()) {
  2676. protocol = GenerateEmptyProtocol(*iter);
  2677. } else {
  2678. protocol = value->getValue();
  2679. }
  2680. Elements.addBitCast(protocol, PtrToInt8Ty);
  2681. }
  2682. Elements.finishAndAddTo(ProtocolList);
  2683. return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
  2684. CGM.getPointerAlign());
  2685. }
  2686. llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
  2687. const ObjCProtocolDecl *PD) {
  2688. llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
  2689. if (!protocol)
  2690. GenerateProtocol(PD);
  2691. llvm::Type *T =
  2692. CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
  2693. return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
  2694. }
  2695. llvm::Constant *
  2696. CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
  2697. llvm::Constant *ProtocolList = GenerateProtocolList({});
  2698. llvm::Constant *MethodList = GenerateProtocolMethodList({});
  2699. MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
  2700. // Protocols are objects containing lists of the methods implemented and
  2701. // protocols adopted.
  2702. ConstantInitBuilder Builder(CGM);
  2703. auto Elements = Builder.beginStruct();
  2704. // The isa pointer must be set to a magic number so the runtime knows it's
  2705. // the correct layout.
  2706. Elements.add(llvm::ConstantExpr::getIntToPtr(
  2707. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  2708. Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
  2709. Elements.add(ProtocolList); /* .protocol_list */
  2710. Elements.add(MethodList); /* .instance_methods */
  2711. Elements.add(MethodList); /* .class_methods */
  2712. Elements.add(MethodList); /* .optional_instance_methods */
  2713. Elements.add(MethodList); /* .optional_class_methods */
  2714. Elements.add(NULLPtr); /* .properties */
  2715. Elements.add(NULLPtr); /* .optional_properties */
  2716. return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
  2717. CGM.getPointerAlign());
  2718. }
  2719. void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
  2720. std::string ProtocolName = PD->getNameAsString();
  2721. // Use the protocol definition, if there is one.
  2722. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  2723. PD = Def;
  2724. SmallVector<std::string, 16> Protocols;
  2725. for (const auto *PI : PD->protocols())
  2726. Protocols.push_back(PI->getNameAsString());
  2727. SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
  2728. SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
  2729. for (const auto *I : PD->instance_methods())
  2730. if (I->isOptional())
  2731. OptionalInstanceMethods.push_back(I);
  2732. else
  2733. InstanceMethods.push_back(I);
  2734. // Collect information about class methods:
  2735. SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
  2736. SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
  2737. for (const auto *I : PD->class_methods())
  2738. if (I->isOptional())
  2739. OptionalClassMethods.push_back(I);
  2740. else
  2741. ClassMethods.push_back(I);
  2742. llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
  2743. llvm::Constant *InstanceMethodList =
  2744. GenerateProtocolMethodList(InstanceMethods);
  2745. llvm::Constant *ClassMethodList =
  2746. GenerateProtocolMethodList(ClassMethods);
  2747. llvm::Constant *OptionalInstanceMethodList =
  2748. GenerateProtocolMethodList(OptionalInstanceMethods);
  2749. llvm::Constant *OptionalClassMethodList =
  2750. GenerateProtocolMethodList(OptionalClassMethods);
  2751. // Property metadata: name, attributes, isSynthesized, setter name, setter
  2752. // types, getter name, getter types.
  2753. // The isSynthesized value is always set to 0 in a protocol. It exists to
  2754. // simplify the runtime library by allowing it to use the same data
  2755. // structures for protocol metadata everywhere.
  2756. llvm::Constant *PropertyList =
  2757. GeneratePropertyList(nullptr, PD, false, false);
  2758. llvm::Constant *OptionalPropertyList =
  2759. GeneratePropertyList(nullptr, PD, false, true);
  2760. // Protocols are objects containing lists of the methods implemented and
  2761. // protocols adopted.
  2762. // The isa pointer must be set to a magic number so the runtime knows it's
  2763. // the correct layout.
  2764. ConstantInitBuilder Builder(CGM);
  2765. auto Elements = Builder.beginStruct();
  2766. Elements.add(
  2767. llvm::ConstantExpr::getIntToPtr(
  2768. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  2769. Elements.add(MakeConstantString(ProtocolName));
  2770. Elements.add(ProtocolList);
  2771. Elements.add(InstanceMethodList);
  2772. Elements.add(ClassMethodList);
  2773. Elements.add(OptionalInstanceMethodList);
  2774. Elements.add(OptionalClassMethodList);
  2775. Elements.add(PropertyList);
  2776. Elements.add(OptionalPropertyList);
  2777. ExistingProtocols[ProtocolName] =
  2778. llvm::ConstantExpr::getBitCast(
  2779. Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
  2780. IdTy);
  2781. }
  2782. void CGObjCGNU::GenerateProtocolHolderCategory() {
  2783. // Collect information about instance methods
  2784. ConstantInitBuilder Builder(CGM);
  2785. auto Elements = Builder.beginStruct();
  2786. const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
  2787. const std::string CategoryName = "AnotherHack";
  2788. Elements.add(MakeConstantString(CategoryName));
  2789. Elements.add(MakeConstantString(ClassName));
  2790. // Instance method list
  2791. Elements.addBitCast(GenerateMethodList(
  2792. ClassName, CategoryName, {}, false), PtrTy);
  2793. // Class method list
  2794. Elements.addBitCast(GenerateMethodList(
  2795. ClassName, CategoryName, {}, true), PtrTy);
  2796. // Protocol list
  2797. ConstantInitBuilder ProtocolListBuilder(CGM);
  2798. auto ProtocolList = ProtocolListBuilder.beginStruct();
  2799. ProtocolList.add(NULLPtr);
  2800. ProtocolList.addInt(LongTy, ExistingProtocols.size());
  2801. auto ProtocolElements = ProtocolList.beginArray(PtrTy);
  2802. for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
  2803. iter != endIter ; iter++) {
  2804. ProtocolElements.addBitCast(iter->getValue(), PtrTy);
  2805. }
  2806. ProtocolElements.finishAndAddTo(ProtocolList);
  2807. Elements.addBitCast(
  2808. ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
  2809. CGM.getPointerAlign()),
  2810. PtrTy);
  2811. Categories.push_back(llvm::ConstantExpr::getBitCast(
  2812. Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
  2813. PtrTy));
  2814. }
  2815. /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
  2816. /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
  2817. /// bits set to their values, LSB first, while larger ones are stored in a
  2818. /// structure of this / form:
  2819. ///
  2820. /// struct { int32_t length; int32_t values[length]; };
  2821. ///
  2822. /// The values in the array are stored in host-endian format, with the least
  2823. /// significant bit being assumed to come first in the bitfield. Therefore, a
  2824. /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
  2825. /// bitfield / with the 63rd bit set will be 1<<64.
  2826. llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
  2827. int bitCount = bits.size();
  2828. int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
  2829. if (bitCount < ptrBits) {
  2830. uint64_t val = 1;
  2831. for (int i=0 ; i<bitCount ; ++i) {
  2832. if (bits[i]) val |= 1ULL<<(i+1);
  2833. }
  2834. return llvm::ConstantInt::get(IntPtrTy, val);
  2835. }
  2836. SmallVector<llvm::Constant *, 8> values;
  2837. int v=0;
  2838. while (v < bitCount) {
  2839. int32_t word = 0;
  2840. for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
  2841. if (bits[v]) word |= 1<<i;
  2842. v++;
  2843. }
  2844. values.push_back(llvm::ConstantInt::get(Int32Ty, word));
  2845. }
  2846. ConstantInitBuilder builder(CGM);
  2847. auto fields = builder.beginStruct();
  2848. fields.addInt(Int32Ty, values.size());
  2849. auto array = fields.beginArray();
  2850. for (auto v : values) array.add(v);
  2851. array.finishAndAddTo(fields);
  2852. llvm::Constant *GS =
  2853. fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
  2854. llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
  2855. return ptr;
  2856. }
  2857. llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
  2858. ObjCCategoryDecl *OCD) {
  2859. SmallVector<std::string, 16> Protocols;
  2860. for (const auto *PD : OCD->getReferencedProtocols())
  2861. Protocols.push_back(PD->getNameAsString());
  2862. return GenerateProtocolList(Protocols);
  2863. }
  2864. void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
  2865. const ObjCInterfaceDecl *Class = OCD->getClassInterface();
  2866. std::string ClassName = Class->getNameAsString();
  2867. std::string CategoryName = OCD->getNameAsString();
  2868. // Collect the names of referenced protocols
  2869. const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
  2870. ConstantInitBuilder Builder(CGM);
  2871. auto Elements = Builder.beginStruct();
  2872. Elements.add(MakeConstantString(CategoryName));
  2873. Elements.add(MakeConstantString(ClassName));
  2874. // Instance method list
  2875. SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
  2876. InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
  2877. OCD->instmeth_end());
  2878. Elements.addBitCast(
  2879. GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
  2880. PtrTy);
  2881. // Class method list
  2882. SmallVector<ObjCMethodDecl*, 16> ClassMethods;
  2883. ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
  2884. OCD->classmeth_end());
  2885. Elements.addBitCast(
  2886. GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
  2887. PtrTy);
  2888. // Protocol list
  2889. Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
  2890. if (isRuntime(ObjCRuntime::GNUstep, 2)) {
  2891. const ObjCCategoryDecl *Category =
  2892. Class->FindCategoryDeclaration(OCD->getIdentifier());
  2893. if (Category) {
  2894. // Instance properties
  2895. Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
  2896. // Class properties
  2897. Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
  2898. } else {
  2899. Elements.addNullPointer(PtrTy);
  2900. Elements.addNullPointer(PtrTy);
  2901. }
  2902. }
  2903. Categories.push_back(llvm::ConstantExpr::getBitCast(
  2904. Elements.finishAndCreateGlobal(
  2905. std::string(".objc_category_")+ClassName+CategoryName,
  2906. CGM.getPointerAlign()),
  2907. PtrTy));
  2908. }
  2909. llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
  2910. const ObjCContainerDecl *OCD,
  2911. bool isClassProperty,
  2912. bool protocolOptionalProperties) {
  2913. SmallVector<const ObjCPropertyDecl *, 16> Properties;
  2914. llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
  2915. bool isProtocol = isa<ObjCProtocolDecl>(OCD);
  2916. ASTContext &Context = CGM.getContext();
  2917. std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
  2918. = [&](const ObjCProtocolDecl *Proto) {
  2919. for (const auto *P : Proto->protocols())
  2920. collectProtocolProperties(P);
  2921. for (const auto *PD : Proto->properties()) {
  2922. if (isClassProperty != PD->isClassProperty())
  2923. continue;
  2924. // Skip any properties that are declared in protocols that this class
  2925. // conforms to but are not actually implemented by this class.
  2926. if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
  2927. continue;
  2928. if (!PropertySet.insert(PD->getIdentifier()).second)
  2929. continue;
  2930. Properties.push_back(PD);
  2931. }
  2932. };
  2933. if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
  2934. for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
  2935. for (auto *PD : ClassExt->properties()) {
  2936. if (isClassProperty != PD->isClassProperty())
  2937. continue;
  2938. PropertySet.insert(PD->getIdentifier());
  2939. Properties.push_back(PD);
  2940. }
  2941. for (const auto *PD : OCD->properties()) {
  2942. if (isClassProperty != PD->isClassProperty())
  2943. continue;
  2944. // If we're generating a list for a protocol, skip optional / required ones
  2945. // when generating the other list.
  2946. if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
  2947. continue;
  2948. // Don't emit duplicate metadata for properties that were already in a
  2949. // class extension.
  2950. if (!PropertySet.insert(PD->getIdentifier()).second)
  2951. continue;
  2952. Properties.push_back(PD);
  2953. }
  2954. if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
  2955. for (const auto *P : OID->all_referenced_protocols())
  2956. collectProtocolProperties(P);
  2957. else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
  2958. for (const auto *P : CD->protocols())
  2959. collectProtocolProperties(P);
  2960. auto numProperties = Properties.size();
  2961. if (numProperties == 0)
  2962. return NULLPtr;
  2963. ConstantInitBuilder builder(CGM);
  2964. auto propertyList = builder.beginStruct();
  2965. auto properties = PushPropertyListHeader(propertyList, numProperties);
  2966. // Add all of the property methods need adding to the method list and to the
  2967. // property metadata list.
  2968. for (auto *property : Properties) {
  2969. bool isSynthesized = false;
  2970. bool isDynamic = false;
  2971. if (!isProtocol) {
  2972. auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
  2973. if (propertyImpl) {
  2974. isSynthesized = (propertyImpl->getPropertyImplementation() ==
  2975. ObjCPropertyImplDecl::Synthesize);
  2976. isDynamic = (propertyImpl->getPropertyImplementation() ==
  2977. ObjCPropertyImplDecl::Dynamic);
  2978. }
  2979. }
  2980. PushProperty(properties, property, Container, isSynthesized, isDynamic);
  2981. }
  2982. properties.finishAndAddTo(propertyList);
  2983. return propertyList.finishAndCreateGlobal(".objc_property_list",
  2984. CGM.getPointerAlign());
  2985. }
  2986. void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
  2987. // Get the class declaration for which the alias is specified.
  2988. ObjCInterfaceDecl *ClassDecl =
  2989. const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
  2990. ClassAliases.emplace_back(ClassDecl->getNameAsString(),
  2991. OAD->getNameAsString());
  2992. }
  2993. void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
  2994. ASTContext &Context = CGM.getContext();
  2995. // Get the superclass name.
  2996. const ObjCInterfaceDecl * SuperClassDecl =
  2997. OID->getClassInterface()->getSuperClass();
  2998. std::string SuperClassName;
  2999. if (SuperClassDecl) {
  3000. SuperClassName = SuperClassDecl->getNameAsString();
  3001. EmitClassRef(SuperClassName);
  3002. }
  3003. // Get the class name
  3004. ObjCInterfaceDecl *ClassDecl =
  3005. const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
  3006. std::string ClassName = ClassDecl->getNameAsString();
  3007. // Emit the symbol that is used to generate linker errors if this class is
  3008. // referenced in other modules but not declared.
  3009. std::string classSymbolName = "__objc_class_name_" + ClassName;
  3010. if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
  3011. symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
  3012. } else {
  3013. new llvm::GlobalVariable(TheModule, LongTy, false,
  3014. llvm::GlobalValue::ExternalLinkage,
  3015. llvm::ConstantInt::get(LongTy, 0),
  3016. classSymbolName);
  3017. }
  3018. // Get the size of instances.
  3019. int instanceSize =
  3020. Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
  3021. // Collect information about instance variables.
  3022. SmallVector<llvm::Constant*, 16> IvarNames;
  3023. SmallVector<llvm::Constant*, 16> IvarTypes;
  3024. SmallVector<llvm::Constant*, 16> IvarOffsets;
  3025. SmallVector<llvm::Constant*, 16> IvarAligns;
  3026. SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
  3027. ConstantInitBuilder IvarOffsetBuilder(CGM);
  3028. auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
  3029. SmallVector<bool, 16> WeakIvars;
  3030. SmallVector<bool, 16> StrongIvars;
  3031. int superInstanceSize = !SuperClassDecl ? 0 :
  3032. Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
  3033. // For non-fragile ivars, set the instance size to 0 - {the size of just this
  3034. // class}. The runtime will then set this to the correct value on load.
  3035. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  3036. instanceSize = 0 - (instanceSize - superInstanceSize);
  3037. }
  3038. for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
  3039. IVD = IVD->getNextIvar()) {
  3040. // Store the name
  3041. IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
  3042. // Get the type encoding for this ivar
  3043. std::string TypeStr;
  3044. Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
  3045. IvarTypes.push_back(MakeConstantString(TypeStr));
  3046. IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
  3047. Context.getTypeSize(IVD->getType())));
  3048. // Get the offset
  3049. uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
  3050. uint64_t Offset = BaseOffset;
  3051. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  3052. Offset = BaseOffset - superInstanceSize;
  3053. }
  3054. llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
  3055. // Create the direct offset value
  3056. std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
  3057. IVD->getNameAsString();
  3058. llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
  3059. if (OffsetVar) {
  3060. OffsetVar->setInitializer(OffsetValue);
  3061. // If this is the real definition, change its linkage type so that
  3062. // different modules will use this one, rather than their private
  3063. // copy.
  3064. OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3065. } else
  3066. OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
  3067. false, llvm::GlobalValue::ExternalLinkage,
  3068. OffsetValue, OffsetName);
  3069. IvarOffsets.push_back(OffsetValue);
  3070. IvarOffsetValues.add(OffsetVar);
  3071. Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
  3072. IvarOwnership.push_back(lt);
  3073. switch (lt) {
  3074. case Qualifiers::OCL_Strong:
  3075. StrongIvars.push_back(true);
  3076. WeakIvars.push_back(false);
  3077. break;
  3078. case Qualifiers::OCL_Weak:
  3079. StrongIvars.push_back(false);
  3080. WeakIvars.push_back(true);
  3081. break;
  3082. default:
  3083. StrongIvars.push_back(false);
  3084. WeakIvars.push_back(false);
  3085. }
  3086. }
  3087. llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
  3088. llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
  3089. llvm::GlobalVariable *IvarOffsetArray =
  3090. IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
  3091. CGM.getPointerAlign());
  3092. // Collect information about instance methods
  3093. SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
  3094. InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
  3095. OID->instmeth_end());
  3096. SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
  3097. ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
  3098. OID->classmeth_end());
  3099. // Collect the same information about synthesized properties, which don't
  3100. // show up in the instance method lists.
  3101. for (auto *propertyImpl : OID->property_impls())
  3102. if (propertyImpl->getPropertyImplementation() ==
  3103. ObjCPropertyImplDecl::Synthesize) {
  3104. ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
  3105. auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
  3106. if (accessor)
  3107. InstanceMethods.push_back(accessor);
  3108. };
  3109. addPropertyMethod(property->getGetterMethodDecl());
  3110. addPropertyMethod(property->getSetterMethodDecl());
  3111. }
  3112. llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
  3113. // Collect the names of referenced protocols
  3114. SmallVector<std::string, 16> Protocols;
  3115. for (const auto *I : ClassDecl->protocols())
  3116. Protocols.push_back(I->getNameAsString());
  3117. // Get the superclass pointer.
  3118. llvm::Constant *SuperClass;
  3119. if (!SuperClassName.empty()) {
  3120. SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
  3121. } else {
  3122. SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
  3123. }
  3124. // Empty vector used to construct empty method lists
  3125. SmallVector<llvm::Constant*, 1> empty;
  3126. // Generate the method and instance variable lists
  3127. llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
  3128. InstanceMethods, false);
  3129. llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
  3130. ClassMethods, true);
  3131. llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
  3132. IvarOffsets, IvarAligns, IvarOwnership);
  3133. // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
  3134. // we emit a symbol containing the offset for each ivar in the class. This
  3135. // allows code compiled for the non-Fragile ABI to inherit from code compiled
  3136. // for the legacy ABI, without causing problems. The converse is also
  3137. // possible, but causes all ivar accesses to be fragile.
  3138. // Offset pointer for getting at the correct field in the ivar list when
  3139. // setting up the alias. These are: The base address for the global, the
  3140. // ivar array (second field), the ivar in this list (set for each ivar), and
  3141. // the offset (third field in ivar structure)
  3142. llvm::Type *IndexTy = Int32Ty;
  3143. llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
  3144. llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
  3145. llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
  3146. unsigned ivarIndex = 0;
  3147. for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
  3148. IVD = IVD->getNextIvar()) {
  3149. const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
  3150. offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
  3151. // Get the correct ivar field
  3152. llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
  3153. cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
  3154. offsetPointerIndexes);
  3155. // Get the existing variable, if one exists.
  3156. llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
  3157. if (offset) {
  3158. offset->setInitializer(offsetValue);
  3159. // If this is the real definition, change its linkage type so that
  3160. // different modules will use this one, rather than their private
  3161. // copy.
  3162. offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3163. } else
  3164. // Add a new alias if there isn't one already.
  3165. new llvm::GlobalVariable(TheModule, offsetValue->getType(),
  3166. false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
  3167. ++ivarIndex;
  3168. }
  3169. llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
  3170. //Generate metaclass for class methods
  3171. llvm::Constant *MetaClassStruct = GenerateClassStructure(
  3172. NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
  3173. NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
  3174. GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
  3175. CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
  3176. OID->getClassInterface());
  3177. // Generate the class structure
  3178. llvm::Constant *ClassStruct = GenerateClassStructure(
  3179. MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
  3180. llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
  3181. GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
  3182. StrongIvarBitmap, WeakIvarBitmap);
  3183. CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
  3184. OID->getClassInterface());
  3185. // Resolve the class aliases, if they exist.
  3186. if (ClassPtrAlias) {
  3187. ClassPtrAlias->replaceAllUsesWith(
  3188. llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
  3189. ClassPtrAlias->eraseFromParent();
  3190. ClassPtrAlias = nullptr;
  3191. }
  3192. if (MetaClassPtrAlias) {
  3193. MetaClassPtrAlias->replaceAllUsesWith(
  3194. llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
  3195. MetaClassPtrAlias->eraseFromParent();
  3196. MetaClassPtrAlias = nullptr;
  3197. }
  3198. // Add class structure to list to be added to the symtab later
  3199. ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
  3200. Classes.push_back(ClassStruct);
  3201. }
  3202. llvm::Function *CGObjCGNU::ModuleInitFunction() {
  3203. // Only emit an ObjC load function if no Objective-C stuff has been called
  3204. if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
  3205. ExistingProtocols.empty() && SelectorTable.empty())
  3206. return nullptr;
  3207. // Add all referenced protocols to a category.
  3208. GenerateProtocolHolderCategory();
  3209. llvm::StructType *selStructTy =
  3210. dyn_cast<llvm::StructType>(SelectorTy->getElementType());
  3211. llvm::Type *selStructPtrTy = SelectorTy;
  3212. if (!selStructTy) {
  3213. selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
  3214. { PtrToInt8Ty, PtrToInt8Ty });
  3215. selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
  3216. }
  3217. // Generate statics list:
  3218. llvm::Constant *statics = NULLPtr;
  3219. if (!ConstantStrings.empty()) {
  3220. llvm::GlobalVariable *fileStatics = [&] {
  3221. ConstantInitBuilder builder(CGM);
  3222. auto staticsStruct = builder.beginStruct();
  3223. StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
  3224. if (stringClass.empty()) stringClass = "NXConstantString";
  3225. staticsStruct.add(MakeConstantString(stringClass,
  3226. ".objc_static_class_name"));
  3227. auto array = staticsStruct.beginArray();
  3228. array.addAll(ConstantStrings);
  3229. array.add(NULLPtr);
  3230. array.finishAndAddTo(staticsStruct);
  3231. return staticsStruct.finishAndCreateGlobal(".objc_statics",
  3232. CGM.getPointerAlign());
  3233. }();
  3234. ConstantInitBuilder builder(CGM);
  3235. auto allStaticsArray = builder.beginArray(fileStatics->getType());
  3236. allStaticsArray.add(fileStatics);
  3237. allStaticsArray.addNullPointer(fileStatics->getType());
  3238. statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
  3239. CGM.getPointerAlign());
  3240. statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
  3241. }
  3242. // Array of classes, categories, and constant objects.
  3243. SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
  3244. unsigned selectorCount;
  3245. // Pointer to an array of selectors used in this module.
  3246. llvm::GlobalVariable *selectorList = [&] {
  3247. ConstantInitBuilder builder(CGM);
  3248. auto selectors = builder.beginArray(selStructTy);
  3249. auto &table = SelectorTable; // MSVC workaround
  3250. std::vector<Selector> allSelectors;
  3251. for (auto &entry : table)
  3252. allSelectors.push_back(entry.first);
  3253. llvm::sort(allSelectors);
  3254. for (auto &untypedSel : allSelectors) {
  3255. std::string selNameStr = untypedSel.getAsString();
  3256. llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
  3257. for (TypedSelector &sel : table[untypedSel]) {
  3258. llvm::Constant *selectorTypeEncoding = NULLPtr;
  3259. if (!sel.first.empty())
  3260. selectorTypeEncoding =
  3261. MakeConstantString(sel.first, ".objc_sel_types");
  3262. auto selStruct = selectors.beginStruct(selStructTy);
  3263. selStruct.add(selName);
  3264. selStruct.add(selectorTypeEncoding);
  3265. selStruct.finishAndAddTo(selectors);
  3266. // Store the selector alias for later replacement
  3267. selectorAliases.push_back(sel.second);
  3268. }
  3269. }
  3270. // Remember the number of entries in the selector table.
  3271. selectorCount = selectors.size();
  3272. // NULL-terminate the selector list. This should not actually be required,
  3273. // because the selector list has a length field. Unfortunately, the GCC
  3274. // runtime decides to ignore the length field and expects a NULL terminator,
  3275. // and GCC cooperates with this by always setting the length to 0.
  3276. auto selStruct = selectors.beginStruct(selStructTy);
  3277. selStruct.add(NULLPtr);
  3278. selStruct.add(NULLPtr);
  3279. selStruct.finishAndAddTo(selectors);
  3280. return selectors.finishAndCreateGlobal(".objc_selector_list",
  3281. CGM.getPointerAlign());
  3282. }();
  3283. // Now that all of the static selectors exist, create pointers to them.
  3284. for (unsigned i = 0; i < selectorCount; ++i) {
  3285. llvm::Constant *idxs[] = {
  3286. Zeros[0],
  3287. llvm::ConstantInt::get(Int32Ty, i)
  3288. };
  3289. // FIXME: We're generating redundant loads and stores here!
  3290. llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
  3291. selectorList->getValueType(), selectorList, idxs);
  3292. // If selectors are defined as an opaque type, cast the pointer to this
  3293. // type.
  3294. selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
  3295. selectorAliases[i]->replaceAllUsesWith(selPtr);
  3296. selectorAliases[i]->eraseFromParent();
  3297. }
  3298. llvm::GlobalVariable *symtab = [&] {
  3299. ConstantInitBuilder builder(CGM);
  3300. auto symtab = builder.beginStruct();
  3301. // Number of static selectors
  3302. symtab.addInt(LongTy, selectorCount);
  3303. symtab.addBitCast(selectorList, selStructPtrTy);
  3304. // Number of classes defined.
  3305. symtab.addInt(CGM.Int16Ty, Classes.size());
  3306. // Number of categories defined
  3307. symtab.addInt(CGM.Int16Ty, Categories.size());
  3308. // Create an array of classes, then categories, then static object instances
  3309. auto classList = symtab.beginArray(PtrToInt8Ty);
  3310. classList.addAll(Classes);
  3311. classList.addAll(Categories);
  3312. // NULL-terminated list of static object instances (mainly constant strings)
  3313. classList.add(statics);
  3314. classList.add(NULLPtr);
  3315. classList.finishAndAddTo(symtab);
  3316. // Construct the symbol table.
  3317. return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
  3318. }();
  3319. // The symbol table is contained in a module which has some version-checking
  3320. // constants
  3321. llvm::Constant *module = [&] {
  3322. llvm::Type *moduleEltTys[] = {
  3323. LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
  3324. };
  3325. llvm::StructType *moduleTy =
  3326. llvm::StructType::get(CGM.getLLVMContext(),
  3327. makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
  3328. ConstantInitBuilder builder(CGM);
  3329. auto module = builder.beginStruct(moduleTy);
  3330. // Runtime version, used for ABI compatibility checking.
  3331. module.addInt(LongTy, RuntimeVersion);
  3332. // sizeof(ModuleTy)
  3333. module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
  3334. // The path to the source file where this module was declared
  3335. SourceManager &SM = CGM.getContext().getSourceManager();
  3336. const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
  3337. std::string path =
  3338. (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
  3339. module.add(MakeConstantString(path, ".objc_source_file_name"));
  3340. module.add(symtab);
  3341. if (RuntimeVersion >= 10) {
  3342. switch (CGM.getLangOpts().getGC()) {
  3343. case LangOptions::GCOnly:
  3344. module.addInt(IntTy, 2);
  3345. break;
  3346. case LangOptions::NonGC:
  3347. if (CGM.getLangOpts().ObjCAutoRefCount)
  3348. module.addInt(IntTy, 1);
  3349. else
  3350. module.addInt(IntTy, 0);
  3351. break;
  3352. case LangOptions::HybridGC:
  3353. module.addInt(IntTy, 1);
  3354. break;
  3355. }
  3356. }
  3357. return module.finishAndCreateGlobal("", CGM.getPointerAlign());
  3358. }();
  3359. // Create the load function calling the runtime entry point with the module
  3360. // structure
  3361. llvm::Function * LoadFunction = llvm::Function::Create(
  3362. llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
  3363. llvm::GlobalValue::InternalLinkage, ".objc_load_function",
  3364. &TheModule);
  3365. llvm::BasicBlock *EntryBB =
  3366. llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
  3367. CGBuilderTy Builder(CGM, VMContext);
  3368. Builder.SetInsertPoint(EntryBB);
  3369. llvm::FunctionType *FT =
  3370. llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
  3371. llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
  3372. Builder.CreateCall(Register, module);
  3373. if (!ClassAliases.empty()) {
  3374. llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
  3375. llvm::FunctionType *RegisterAliasTy =
  3376. llvm::FunctionType::get(Builder.getVoidTy(),
  3377. ArgTypes, false);
  3378. llvm::Function *RegisterAlias = llvm::Function::Create(
  3379. RegisterAliasTy,
  3380. llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
  3381. &TheModule);
  3382. llvm::BasicBlock *AliasBB =
  3383. llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
  3384. llvm::BasicBlock *NoAliasBB =
  3385. llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
  3386. // Branch based on whether the runtime provided class_registerAlias_np()
  3387. llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
  3388. llvm::Constant::getNullValue(RegisterAlias->getType()));
  3389. Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
  3390. // The true branch (has alias registration function):
  3391. Builder.SetInsertPoint(AliasBB);
  3392. // Emit alias registration calls:
  3393. for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
  3394. iter != ClassAliases.end(); ++iter) {
  3395. llvm::Constant *TheClass =
  3396. TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
  3397. if (TheClass) {
  3398. TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
  3399. Builder.CreateCall(RegisterAlias,
  3400. {TheClass, MakeConstantString(iter->second)});
  3401. }
  3402. }
  3403. // Jump to end:
  3404. Builder.CreateBr(NoAliasBB);
  3405. // Missing alias registration function, just return from the function:
  3406. Builder.SetInsertPoint(NoAliasBB);
  3407. }
  3408. Builder.CreateRetVoid();
  3409. return LoadFunction;
  3410. }
  3411. llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
  3412. const ObjCContainerDecl *CD) {
  3413. const ObjCCategoryImplDecl *OCD =
  3414. dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
  3415. StringRef CategoryName = OCD ? OCD->getName() : "";
  3416. StringRef ClassName = CD->getName();
  3417. Selector MethodName = OMD->getSelector();
  3418. bool isClassMethod = !OMD->isInstanceMethod();
  3419. CodeGenTypes &Types = CGM.getTypes();
  3420. llvm::FunctionType *MethodTy =
  3421. Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
  3422. std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
  3423. MethodName, isClassMethod);
  3424. llvm::Function *Method
  3425. = llvm::Function::Create(MethodTy,
  3426. llvm::GlobalValue::InternalLinkage,
  3427. FunctionName,
  3428. &TheModule);
  3429. return Method;
  3430. }
  3431. llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
  3432. return GetPropertyFn;
  3433. }
  3434. llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
  3435. return SetPropertyFn;
  3436. }
  3437. llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
  3438. bool copy) {
  3439. return nullptr;
  3440. }
  3441. llvm::Constant *CGObjCGNU::GetGetStructFunction() {
  3442. return GetStructPropertyFn;
  3443. }
  3444. llvm::Constant *CGObjCGNU::GetSetStructFunction() {
  3445. return SetStructPropertyFn;
  3446. }
  3447. llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
  3448. return nullptr;
  3449. }
  3450. llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
  3451. return nullptr;
  3452. }
  3453. llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
  3454. return EnumerationMutationFn;
  3455. }
  3456. void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
  3457. const ObjCAtSynchronizedStmt &S) {
  3458. EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
  3459. }
  3460. void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
  3461. const ObjCAtTryStmt &S) {
  3462. // Unlike the Apple non-fragile runtimes, which also uses
  3463. // unwind-based zero cost exceptions, the GNU Objective C runtime's
  3464. // EH support isn't a veneer over C++ EH. Instead, exception
  3465. // objects are created by objc_exception_throw and destroyed by
  3466. // the personality function; this avoids the need for bracketing
  3467. // catch handlers with calls to __blah_begin_catch/__blah_end_catch
  3468. // (or even _Unwind_DeleteException), but probably doesn't
  3469. // interoperate very well with foreign exceptions.
  3470. //
  3471. // In Objective-C++ mode, we actually emit something equivalent to the C++
  3472. // exception handler.
  3473. EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
  3474. }
  3475. void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
  3476. const ObjCAtThrowStmt &S,
  3477. bool ClearInsertionPoint) {
  3478. llvm::Value *ExceptionAsObject;
  3479. bool isRethrow = false;
  3480. if (const Expr *ThrowExpr = S.getThrowExpr()) {
  3481. llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
  3482. ExceptionAsObject = Exception;
  3483. } else {
  3484. assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
  3485. "Unexpected rethrow outside @catch block.");
  3486. ExceptionAsObject = CGF.ObjCEHValueStack.back();
  3487. isRethrow = true;
  3488. }
  3489. if (isRethrow && usesSEHExceptions) {
  3490. // For SEH, ExceptionAsObject may be undef, because the catch handler is
  3491. // not passed it for catchalls and so it is not visible to the catch
  3492. // funclet. The real thrown object will still be live on the stack at this
  3493. // point and will be rethrown. If we are explicitly rethrowing the object
  3494. // that was passed into the `@catch` block, then this code path is not
  3495. // reached and we will instead call `objc_exception_throw` with an explicit
  3496. // argument.
  3497. llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
  3498. Throw->setDoesNotReturn();
  3499. }
  3500. else {
  3501. ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
  3502. llvm::CallBase *Throw =
  3503. CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
  3504. Throw->setDoesNotReturn();
  3505. }
  3506. CGF.Builder.CreateUnreachable();
  3507. if (ClearInsertionPoint)
  3508. CGF.Builder.ClearInsertionPoint();
  3509. }
  3510. llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
  3511. Address AddrWeakObj) {
  3512. CGBuilderTy &B = CGF.Builder;
  3513. AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
  3514. return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
  3515. AddrWeakObj.getPointer());
  3516. }
  3517. void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
  3518. llvm::Value *src, Address dst) {
  3519. CGBuilderTy &B = CGF.Builder;
  3520. src = EnforceType(B, src, IdTy);
  3521. dst = EnforceType(B, dst, PtrToIdTy);
  3522. B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
  3523. {src, dst.getPointer()});
  3524. }
  3525. void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
  3526. llvm::Value *src, Address dst,
  3527. bool threadlocal) {
  3528. CGBuilderTy &B = CGF.Builder;
  3529. src = EnforceType(B, src, IdTy);
  3530. dst = EnforceType(B, dst, PtrToIdTy);
  3531. // FIXME. Add threadloca assign API
  3532. assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
  3533. B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
  3534. {src, dst.getPointer()});
  3535. }
  3536. void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
  3537. llvm::Value *src, Address dst,
  3538. llvm::Value *ivarOffset) {
  3539. CGBuilderTy &B = CGF.Builder;
  3540. src = EnforceType(B, src, IdTy);
  3541. dst = EnforceType(B, dst, IdTy);
  3542. B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
  3543. {src, dst.getPointer(), ivarOffset});
  3544. }
  3545. void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
  3546. llvm::Value *src, Address dst) {
  3547. CGBuilderTy &B = CGF.Builder;
  3548. src = EnforceType(B, src, IdTy);
  3549. dst = EnforceType(B, dst, PtrToIdTy);
  3550. B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
  3551. {src, dst.getPointer()});
  3552. }
  3553. void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
  3554. Address DestPtr,
  3555. Address SrcPtr,
  3556. llvm::Value *Size) {
  3557. CGBuilderTy &B = CGF.Builder;
  3558. DestPtr = EnforceType(B, DestPtr, PtrTy);
  3559. SrcPtr = EnforceType(B, SrcPtr, PtrTy);
  3560. B.CreateCall(MemMoveFn.getType(), MemMoveFn,
  3561. {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
  3562. }
  3563. llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
  3564. const ObjCInterfaceDecl *ID,
  3565. const ObjCIvarDecl *Ivar) {
  3566. const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
  3567. // Emit the variable and initialize it with what we think the correct value
  3568. // is. This allows code compiled with non-fragile ivars to work correctly
  3569. // when linked against code which isn't (most of the time).
  3570. llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
  3571. if (!IvarOffsetPointer)
  3572. IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
  3573. llvm::Type::getInt32PtrTy(VMContext), false,
  3574. llvm::GlobalValue::ExternalLinkage, nullptr, Name);
  3575. return IvarOffsetPointer;
  3576. }
  3577. LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
  3578. QualType ObjectTy,
  3579. llvm::Value *BaseValue,
  3580. const ObjCIvarDecl *Ivar,
  3581. unsigned CVRQualifiers) {
  3582. const ObjCInterfaceDecl *ID =
  3583. ObjectTy->getAs<ObjCObjectType>()->getInterface();
  3584. return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
  3585. EmitIvarOffset(CGF, ID, Ivar));
  3586. }
  3587. static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
  3588. const ObjCInterfaceDecl *OID,
  3589. const ObjCIvarDecl *OIVD) {
  3590. for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
  3591. next = next->getNextIvar()) {
  3592. if (OIVD == next)
  3593. return OID;
  3594. }
  3595. // Otherwise check in the super class.
  3596. if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
  3597. return FindIvarInterface(Context, Super, OIVD);
  3598. return nullptr;
  3599. }
  3600. llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
  3601. const ObjCInterfaceDecl *Interface,
  3602. const ObjCIvarDecl *Ivar) {
  3603. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  3604. Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
  3605. // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
  3606. // and ExternalLinkage, so create a reference to the ivar global and rely on
  3607. // the definition being created as part of GenerateClass.
  3608. if (RuntimeVersion < 10 ||
  3609. CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
  3610. return CGF.Builder.CreateZExtOrBitCast(
  3611. CGF.Builder.CreateAlignedLoad(
  3612. Int32Ty, CGF.Builder.CreateAlignedLoad(
  3613. ObjCIvarOffsetVariable(Interface, Ivar),
  3614. CGF.getPointerAlign(), "ivar"),
  3615. CharUnits::fromQuantity(4)),
  3616. PtrDiffTy);
  3617. std::string name = "__objc_ivar_offset_value_" +
  3618. Interface->getNameAsString() +"." + Ivar->getNameAsString();
  3619. CharUnits Align = CGM.getIntAlign();
  3620. llvm::Value *Offset = TheModule.getGlobalVariable(name);
  3621. if (!Offset) {
  3622. auto GV = new llvm::GlobalVariable(TheModule, IntTy,
  3623. false, llvm::GlobalValue::LinkOnceAnyLinkage,
  3624. llvm::Constant::getNullValue(IntTy), name);
  3625. GV->setAlignment(Align.getQuantity());
  3626. Offset = GV;
  3627. }
  3628. Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
  3629. if (Offset->getType() != PtrDiffTy)
  3630. Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
  3631. return Offset;
  3632. }
  3633. uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
  3634. return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
  3635. }
  3636. CGObjCRuntime *
  3637. clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
  3638. auto Runtime = CGM.getLangOpts().ObjCRuntime;
  3639. switch (Runtime.getKind()) {
  3640. case ObjCRuntime::GNUstep:
  3641. if (Runtime.getVersion() >= VersionTuple(2, 0))
  3642. return new CGObjCGNUstep2(CGM);
  3643. return new CGObjCGNUstep(CGM);
  3644. case ObjCRuntime::GCC:
  3645. return new CGObjCGCC(CGM);
  3646. case ObjCRuntime::ObjFW:
  3647. return new CGObjCObjFW(CGM);
  3648. case ObjCRuntime::FragileMacOSX:
  3649. case ObjCRuntime::MacOSX:
  3650. case ObjCRuntime::iOS:
  3651. case ObjCRuntime::WatchOS:
  3652. llvm_unreachable("these runtimes are not GNU runtimes");
  3653. }
  3654. llvm_unreachable("bad runtime");
  3655. }