CGObjCGNU.cpp 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926
  1. //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This provides Objective-C code generation targeting the GNU runtime. The
  11. // class in this file generates structures used by the GNU Objective-C runtime
  12. // library. These structures are defined in objc/objc.h and objc/objc-api.h in
  13. // the GNU runtime distribution.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "CGObjCRuntime.h"
  17. #include "CGCleanup.h"
  18. #include "CodeGenFunction.h"
  19. #include "CodeGenModule.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/Decl.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/RecordLayout.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/Basic/FileManager.h"
  26. #include "clang/Basic/SourceManager.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/StringMap.h"
  29. #include "llvm/IR/CallSite.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 <cstdarg>
  36. using namespace clang;
  37. using namespace CodeGen;
  38. namespace {
  39. /// Class that lazily initialises the runtime function. Avoids inserting the
  40. /// types and the function declaration into a module if they're not used, and
  41. /// avoids constructing the type more than once if it's used more than once.
  42. class LazyRuntimeFunction {
  43. CodeGenModule *CGM;
  44. llvm::FunctionType *FTy;
  45. const char *FunctionName;
  46. llvm::Constant *Function;
  47. public:
  48. /// Constructor leaves this class uninitialized, because it is intended to
  49. /// be used as a field in another class and not all of the types that are
  50. /// used as arguments will necessarily be available at construction time.
  51. LazyRuntimeFunction()
  52. : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
  53. /// Initialises the lazy function with the name, return type, and the types
  54. /// of the arguments.
  55. LLVM_END_WITH_NULL
  56. void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, ...) {
  57. CGM = Mod;
  58. FunctionName = name;
  59. Function = nullptr;
  60. std::vector<llvm::Type *> ArgTys;
  61. va_list Args;
  62. va_start(Args, RetTy);
  63. while (llvm::Type *ArgTy = va_arg(Args, llvm::Type *))
  64. ArgTys.push_back(ArgTy);
  65. va_end(Args);
  66. FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
  67. }
  68. llvm::FunctionType *getType() { return FTy; }
  69. /// Overloaded cast operator, allows the class to be implicitly cast to an
  70. /// LLVM constant.
  71. operator llvm::Constant *() {
  72. if (!Function) {
  73. if (!FunctionName)
  74. return nullptr;
  75. Function =
  76. cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
  77. }
  78. return Function;
  79. }
  80. operator llvm::Function *() {
  81. return cast<llvm::Function>((llvm::Constant *)*this);
  82. }
  83. };
  84. /// GNU Objective-C runtime code generation. This class implements the parts of
  85. /// Objective-C support that are specific to the GNU family of runtimes (GCC,
  86. /// GNUstep and ObjFW).
  87. class CGObjCGNU : public CGObjCRuntime {
  88. protected:
  89. /// The LLVM module into which output is inserted
  90. llvm::Module &TheModule;
  91. /// strut objc_super. Used for sending messages to super. This structure
  92. /// contains the receiver (object) and the expected class.
  93. llvm::StructType *ObjCSuperTy;
  94. /// struct objc_super*. The type of the argument to the superclass message
  95. /// lookup functions.
  96. llvm::PointerType *PtrToObjCSuperTy;
  97. /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
  98. /// SEL is included in a header somewhere, in which case it will be whatever
  99. /// type is declared in that header, most likely {i8*, i8*}.
  100. llvm::PointerType *SelectorTy;
  101. /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
  102. /// places where it's used
  103. llvm::IntegerType *Int8Ty;
  104. /// Pointer to i8 - LLVM type of char*, for all of the places where the
  105. /// runtime needs to deal with C strings.
  106. llvm::PointerType *PtrToInt8Ty;
  107. /// Instance Method Pointer type. This is a pointer to a function that takes,
  108. /// at a minimum, an object and a selector, and is the generic type for
  109. /// Objective-C methods. Due to differences between variadic / non-variadic
  110. /// calling conventions, it must always be cast to the correct type before
  111. /// actually being used.
  112. llvm::PointerType *IMPTy;
  113. /// Type of an untyped Objective-C object. Clang treats id as a built-in type
  114. /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
  115. /// but if the runtime header declaring it is included then it may be a
  116. /// pointer to a structure.
  117. llvm::PointerType *IdTy;
  118. /// Pointer to a pointer to an Objective-C object. Used in the new ABI
  119. /// message lookup function and some GC-related functions.
  120. llvm::PointerType *PtrToIdTy;
  121. /// The clang type of id. Used when using the clang CGCall infrastructure to
  122. /// call Objective-C methods.
  123. CanQualType ASTIdTy;
  124. /// LLVM type for C int type.
  125. llvm::IntegerType *IntTy;
  126. /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
  127. /// used in the code to document the difference between i8* meaning a pointer
  128. /// to a C string and i8* meaning a pointer to some opaque type.
  129. llvm::PointerType *PtrTy;
  130. /// LLVM type for C long type. The runtime uses this in a lot of places where
  131. /// it should be using intptr_t, but we can't fix this without breaking
  132. /// compatibility with GCC...
  133. llvm::IntegerType *LongTy;
  134. /// LLVM type for C size_t. Used in various runtime data structures.
  135. llvm::IntegerType *SizeTy;
  136. /// LLVM type for C intptr_t.
  137. llvm::IntegerType *IntPtrTy;
  138. /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
  139. llvm::IntegerType *PtrDiffTy;
  140. /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
  141. /// variables.
  142. llvm::PointerType *PtrToIntTy;
  143. /// LLVM type for Objective-C BOOL type.
  144. llvm::Type *BoolTy;
  145. /// 32-bit integer type, to save us needing to look it up every time it's used.
  146. llvm::IntegerType *Int32Ty;
  147. /// 64-bit integer type, to save us needing to look it up every time it's used.
  148. llvm::IntegerType *Int64Ty;
  149. /// Metadata kind used to tie method lookups to message sends. The GNUstep
  150. /// runtime provides some LLVM passes that can use this to do things like
  151. /// automatic IMP caching and speculative inlining.
  152. unsigned msgSendMDKind;
  153. /// Helper function that generates a constant string and returns a pointer to
  154. /// the start of the string. The result of this function can be used anywhere
  155. /// where the C code specifies const char*.
  156. llvm::Constant *MakeConstantString(const std::string &Str,
  157. const std::string &Name="") {
  158. ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name.c_str());
  159. return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
  160. Array.getPointer(), Zeros);
  161. }
  162. /// Emits a linkonce_odr string, whose name is the prefix followed by the
  163. /// string value. This allows the linker to combine the strings between
  164. /// different modules. Used for EH typeinfo names, selector strings, and a
  165. /// few other things.
  166. llvm::Constant *ExportUniqueString(const std::string &Str,
  167. const std::string prefix) {
  168. std::string name = prefix + Str;
  169. auto *ConstStr = TheModule.getGlobalVariable(name);
  170. if (!ConstStr) {
  171. llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
  172. ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
  173. llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
  174. }
  175. return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
  176. ConstStr, Zeros);
  177. }
  178. /// Generates a global structure, initialized by the elements in the vector.
  179. /// The element types must match the types of the structure elements in the
  180. /// first argument.
  181. llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
  182. ArrayRef<llvm::Constant *> V,
  183. CharUnits Align,
  184. StringRef Name="",
  185. llvm::GlobalValue::LinkageTypes linkage
  186. =llvm::GlobalValue::InternalLinkage) {
  187. llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
  188. auto GV = new llvm::GlobalVariable(TheModule, Ty, false,
  189. linkage, C, Name);
  190. GV->setAlignment(Align.getQuantity());
  191. return GV;
  192. }
  193. /// Generates a global array. The vector must contain the same number of
  194. /// elements that the array type declares, of the type specified as the array
  195. /// element type.
  196. llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
  197. ArrayRef<llvm::Constant *> V,
  198. CharUnits Align,
  199. StringRef Name="",
  200. llvm::GlobalValue::LinkageTypes linkage
  201. =llvm::GlobalValue::InternalLinkage) {
  202. llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
  203. auto GV = new llvm::GlobalVariable(TheModule, Ty, false,
  204. linkage, C, Name);
  205. GV->setAlignment(Align.getQuantity());
  206. return GV;
  207. }
  208. /// Generates a global array, inferring the array type from the specified
  209. /// element type and the size of the initialiser.
  210. llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
  211. ArrayRef<llvm::Constant *> V,
  212. CharUnits Align,
  213. StringRef Name="",
  214. llvm::GlobalValue::LinkageTypes linkage
  215. =llvm::GlobalValue::InternalLinkage) {
  216. llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
  217. return MakeGlobal(ArrayTy, V, Align, Name, linkage);
  218. }
  219. /// Returns a property name and encoding string.
  220. llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
  221. const Decl *Container) {
  222. const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
  223. if ((R.getKind() == ObjCRuntime::GNUstep) &&
  224. (R.getVersion() >= VersionTuple(1, 6))) {
  225. std::string NameAndAttributes;
  226. std::string TypeStr;
  227. CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
  228. NameAndAttributes += '\0';
  229. NameAndAttributes += TypeStr.length() + 3;
  230. NameAndAttributes += TypeStr;
  231. NameAndAttributes += '\0';
  232. NameAndAttributes += PD->getNameAsString();
  233. return MakeConstantString(NameAndAttributes);
  234. }
  235. return MakeConstantString(PD->getNameAsString());
  236. }
  237. /// Push the property attributes into two structure fields.
  238. void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
  239. ObjCPropertyDecl *property, bool isSynthesized=true, bool
  240. isDynamic=true) {
  241. int attrs = property->getPropertyAttributes();
  242. // For read-only properties, clear the copy and retain flags
  243. if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
  244. attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
  245. attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
  246. attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
  247. attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
  248. }
  249. // The first flags field has the same attribute values as clang uses internally
  250. Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
  251. attrs >>= 8;
  252. attrs <<= 2;
  253. // For protocol properties, synthesized and dynamic have no meaning, so we
  254. // reuse these flags to indicate that this is a protocol property (both set
  255. // has no meaning, as a property can't be both synthesized and dynamic)
  256. attrs |= isSynthesized ? (1<<0) : 0;
  257. attrs |= isDynamic ? (1<<1) : 0;
  258. // The second field is the next four fields left shifted by two, with the
  259. // low bit set to indicate whether the field is synthesized or dynamic.
  260. Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
  261. // Two padding fields
  262. Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
  263. Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
  264. }
  265. /// Ensures that the value has the required type, by inserting a bitcast if
  266. /// required. This function lets us avoid inserting bitcasts that are
  267. /// redundant.
  268. llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
  269. if (V->getType() == Ty) return V;
  270. return B.CreateBitCast(V, Ty);
  271. }
  272. Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
  273. if (V.getType() == Ty) return V;
  274. return B.CreateBitCast(V, Ty);
  275. }
  276. // Some zeros used for GEPs in lots of places.
  277. llvm::Constant *Zeros[2];
  278. /// Null pointer value. Mainly used as a terminator in various arrays.
  279. llvm::Constant *NULLPtr;
  280. /// LLVM context.
  281. llvm::LLVMContext &VMContext;
  282. private:
  283. /// Placeholder for the class. Lots of things refer to the class before we've
  284. /// actually emitted it. We use this alias as a placeholder, and then replace
  285. /// it with a pointer to the class structure before finally emitting the
  286. /// module.
  287. llvm::GlobalAlias *ClassPtrAlias;
  288. /// Placeholder for the metaclass. Lots of things refer to the class before
  289. /// we've / actually emitted it. We use this alias as a placeholder, and then
  290. /// replace / it with a pointer to the metaclass structure before finally
  291. /// emitting the / module.
  292. llvm::GlobalAlias *MetaClassPtrAlias;
  293. /// All of the classes that have been generated for this compilation units.
  294. std::vector<llvm::Constant*> Classes;
  295. /// All of the categories that have been generated for this compilation units.
  296. std::vector<llvm::Constant*> Categories;
  297. /// All of the Objective-C constant strings that have been generated for this
  298. /// compilation units.
  299. std::vector<llvm::Constant*> ConstantStrings;
  300. /// Map from string values to Objective-C constant strings in the output.
  301. /// Used to prevent emitting Objective-C strings more than once. This should
  302. /// not be required at all - CodeGenModule should manage this list.
  303. llvm::StringMap<llvm::Constant*> ObjCStrings;
  304. /// All of the protocols that have been declared.
  305. llvm::StringMap<llvm::Constant*> ExistingProtocols;
  306. /// For each variant of a selector, we store the type encoding and a
  307. /// placeholder value. For an untyped selector, the type will be the empty
  308. /// string. Selector references are all done via the module's selector table,
  309. /// so we create an alias as a placeholder and then replace it with the real
  310. /// value later.
  311. typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
  312. /// Type of the selector map. This is roughly equivalent to the structure
  313. /// used in the GNUstep runtime, which maintains a list of all of the valid
  314. /// types for a selector in a table.
  315. typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
  316. SelectorMap;
  317. /// A map from selectors to selector types. This allows us to emit all
  318. /// selectors of the same name and type together.
  319. SelectorMap SelectorTable;
  320. /// Selectors related to memory management. When compiling in GC mode, we
  321. /// omit these.
  322. Selector RetainSel, ReleaseSel, AutoreleaseSel;
  323. /// Runtime functions used for memory management in GC mode. Note that clang
  324. /// supports code generation for calling these functions, but neither GNU
  325. /// runtime actually supports this API properly yet.
  326. LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
  327. WeakAssignFn, GlobalAssignFn;
  328. typedef std::pair<std::string, std::string> ClassAliasPair;
  329. /// All classes that have aliases set for them.
  330. std::vector<ClassAliasPair> ClassAliases;
  331. protected:
  332. /// Function used for throwing Objective-C exceptions.
  333. LazyRuntimeFunction ExceptionThrowFn;
  334. /// Function used for rethrowing exceptions, used at the end of \@finally or
  335. /// \@synchronize blocks.
  336. LazyRuntimeFunction ExceptionReThrowFn;
  337. /// Function called when entering a catch function. This is required for
  338. /// differentiating Objective-C exceptions and foreign exceptions.
  339. LazyRuntimeFunction EnterCatchFn;
  340. /// Function called when exiting from a catch block. Used to do exception
  341. /// cleanup.
  342. LazyRuntimeFunction ExitCatchFn;
  343. /// Function called when entering an \@synchronize block. Acquires the lock.
  344. LazyRuntimeFunction SyncEnterFn;
  345. /// Function called when exiting an \@synchronize block. Releases the lock.
  346. LazyRuntimeFunction SyncExitFn;
  347. private:
  348. /// Function called if fast enumeration detects that the collection is
  349. /// modified during the update.
  350. LazyRuntimeFunction EnumerationMutationFn;
  351. /// Function for implementing synthesized property getters that return an
  352. /// object.
  353. LazyRuntimeFunction GetPropertyFn;
  354. /// Function for implementing synthesized property setters that return an
  355. /// object.
  356. LazyRuntimeFunction SetPropertyFn;
  357. /// Function used for non-object declared property getters.
  358. LazyRuntimeFunction GetStructPropertyFn;
  359. /// Function used for non-object declared property setters.
  360. LazyRuntimeFunction SetStructPropertyFn;
  361. /// The version of the runtime that this class targets. Must match the
  362. /// version in the runtime.
  363. int RuntimeVersion;
  364. /// The version of the protocol class. Used to differentiate between ObjC1
  365. /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
  366. /// components and can not contain declared properties. We always emit
  367. /// Objective-C 2 property structures, but we have to pretend that they're
  368. /// Objective-C 1 property structures when targeting the GCC runtime or it
  369. /// will abort.
  370. const int ProtocolVersion;
  371. /// Generates an instance variable list structure. This is a structure
  372. /// containing a size and an array of structures containing instance variable
  373. /// metadata. This is used purely for introspection in the fragile ABI. In
  374. /// the non-fragile ABI, it's used for instance variable fixup.
  375. llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
  376. ArrayRef<llvm::Constant *> IvarTypes,
  377. ArrayRef<llvm::Constant *> IvarOffsets);
  378. /// Generates a method list structure. This is a structure containing a size
  379. /// and an array of structures containing method metadata.
  380. ///
  381. /// This structure is used by both classes and categories, and contains a next
  382. /// pointer allowing them to be chained together in a linked list.
  383. llvm::Constant *GenerateMethodList(StringRef ClassName,
  384. StringRef CategoryName,
  385. ArrayRef<Selector> MethodSels,
  386. ArrayRef<llvm::Constant *> MethodTypes,
  387. bool isClassMethodList);
  388. /// Emits an empty protocol. This is used for \@protocol() where no protocol
  389. /// is found. The runtime will (hopefully) fix up the pointer to refer to the
  390. /// real protocol.
  391. llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
  392. /// Generates a list of property metadata structures. This follows the same
  393. /// pattern as method and instance variable metadata lists.
  394. llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
  395. SmallVectorImpl<Selector> &InstanceMethodSels,
  396. SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
  397. /// Generates a list of referenced protocols. Classes, categories, and
  398. /// protocols all use this structure.
  399. llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
  400. /// To ensure that all protocols are seen by the runtime, we add a category on
  401. /// a class defined in the runtime, declaring no methods, but adopting the
  402. /// protocols. This is a horribly ugly hack, but it allows us to collect all
  403. /// of the protocols without changing the ABI.
  404. void GenerateProtocolHolderCategory();
  405. /// Generates a class structure.
  406. llvm::Constant *GenerateClassStructure(
  407. llvm::Constant *MetaClass,
  408. llvm::Constant *SuperClass,
  409. unsigned info,
  410. const char *Name,
  411. llvm::Constant *Version,
  412. llvm::Constant *InstanceSize,
  413. llvm::Constant *IVars,
  414. llvm::Constant *Methods,
  415. llvm::Constant *Protocols,
  416. llvm::Constant *IvarOffsets,
  417. llvm::Constant *Properties,
  418. llvm::Constant *StrongIvarBitmap,
  419. llvm::Constant *WeakIvarBitmap,
  420. bool isMeta=false);
  421. /// Generates a method list. This is used by protocols to define the required
  422. /// and optional methods.
  423. llvm::Constant *GenerateProtocolMethodList(
  424. ArrayRef<llvm::Constant *> MethodNames,
  425. ArrayRef<llvm::Constant *> MethodTypes);
  426. /// Returns a selector with the specified type encoding. An empty string is
  427. /// used to return an untyped selector (with the types field set to NULL).
  428. llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
  429. const std::string &TypeEncoding);
  430. /// Returns the variable used to store the offset of an instance variable.
  431. llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
  432. const ObjCIvarDecl *Ivar);
  433. /// Emits a reference to a class. This allows the linker to object if there
  434. /// is no class of the matching name.
  435. protected:
  436. void EmitClassRef(const std::string &className);
  437. /// Emits a pointer to the named class
  438. virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
  439. const std::string &Name, bool isWeak);
  440. /// Looks up the method for sending a message to the specified object. This
  441. /// mechanism differs between the GCC and GNU runtimes, so this method must be
  442. /// overridden in subclasses.
  443. virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
  444. llvm::Value *&Receiver,
  445. llvm::Value *cmd,
  446. llvm::MDNode *node,
  447. MessageSendInfo &MSI) = 0;
  448. /// Looks up the method for sending a message to a superclass. This
  449. /// mechanism differs between the GCC and GNU runtimes, so this method must
  450. /// be overridden in subclasses.
  451. virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
  452. Address ObjCSuper,
  453. llvm::Value *cmd,
  454. MessageSendInfo &MSI) = 0;
  455. /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
  456. /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
  457. /// bits set to their values, LSB first, while larger ones are stored in a
  458. /// structure of this / form:
  459. ///
  460. /// struct { int32_t length; int32_t values[length]; };
  461. ///
  462. /// The values in the array are stored in host-endian format, with the least
  463. /// significant bit being assumed to come first in the bitfield. Therefore,
  464. /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
  465. /// while a bitfield / with the 63rd bit set will be 1<<64.
  466. llvm::Constant *MakeBitField(ArrayRef<bool> bits);
  467. public:
  468. CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
  469. unsigned protocolClassVersion);
  470. ConstantAddress GenerateConstantString(const StringLiteral *) override;
  471. RValue
  472. GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
  473. QualType ResultType, Selector Sel,
  474. llvm::Value *Receiver, const CallArgList &CallArgs,
  475. const ObjCInterfaceDecl *Class,
  476. const ObjCMethodDecl *Method) override;
  477. RValue
  478. GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
  479. QualType ResultType, Selector Sel,
  480. const ObjCInterfaceDecl *Class,
  481. bool isCategoryImpl, llvm::Value *Receiver,
  482. bool IsClassMessage, const CallArgList &CallArgs,
  483. const ObjCMethodDecl *Method) override;
  484. llvm::Value *GetClass(CodeGenFunction &CGF,
  485. const ObjCInterfaceDecl *OID) override;
  486. llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
  487. Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
  488. llvm::Value *GetSelector(CodeGenFunction &CGF,
  489. const ObjCMethodDecl *Method) override;
  490. llvm::Constant *GetEHType(QualType T) override;
  491. llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
  492. const ObjCContainerDecl *CD) override;
  493. void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
  494. void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
  495. void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
  496. llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
  497. const ObjCProtocolDecl *PD) override;
  498. void GenerateProtocol(const ObjCProtocolDecl *PD) override;
  499. llvm::Function *ModuleInitFunction() override;
  500. llvm::Constant *GetPropertyGetFunction() override;
  501. llvm::Constant *GetPropertySetFunction() override;
  502. llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
  503. bool copy) override;
  504. llvm::Constant *GetSetStructFunction() override;
  505. llvm::Constant *GetGetStructFunction() override;
  506. llvm::Constant *GetCppAtomicObjectGetFunction() override;
  507. llvm::Constant *GetCppAtomicObjectSetFunction() override;
  508. llvm::Constant *EnumerationMutationFunction() override;
  509. void EmitTryStmt(CodeGenFunction &CGF,
  510. const ObjCAtTryStmt &S) override;
  511. void EmitSynchronizedStmt(CodeGenFunction &CGF,
  512. const ObjCAtSynchronizedStmt &S) override;
  513. void EmitThrowStmt(CodeGenFunction &CGF,
  514. const ObjCAtThrowStmt &S,
  515. bool ClearInsertionPoint=true) override;
  516. llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
  517. Address AddrWeakObj) override;
  518. void EmitObjCWeakAssign(CodeGenFunction &CGF,
  519. llvm::Value *src, Address dst) override;
  520. void EmitObjCGlobalAssign(CodeGenFunction &CGF,
  521. llvm::Value *src, Address dest,
  522. bool threadlocal=false) override;
  523. void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
  524. Address dest, llvm::Value *ivarOffset) override;
  525. void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
  526. llvm::Value *src, Address dest) override;
  527. void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
  528. Address SrcPtr,
  529. llvm::Value *Size) override;
  530. LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
  531. llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
  532. unsigned CVRQualifiers) override;
  533. llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
  534. const ObjCInterfaceDecl *Interface,
  535. const ObjCIvarDecl *Ivar) override;
  536. llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
  537. llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
  538. const CGBlockInfo &blockInfo) override {
  539. return NULLPtr;
  540. }
  541. llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
  542. const CGBlockInfo &blockInfo) override {
  543. return NULLPtr;
  544. }
  545. llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
  546. return NULLPtr;
  547. }
  548. llvm::GlobalVariable *GetClassGlobal(StringRef Name,
  549. bool Weak = false) override {
  550. return nullptr;
  551. }
  552. };
  553. /// Class representing the legacy GCC Objective-C ABI. This is the default when
  554. /// -fobjc-nonfragile-abi is not specified.
  555. ///
  556. /// The GCC ABI target actually generates code that is approximately compatible
  557. /// with the new GNUstep runtime ABI, but refrains from using any features that
  558. /// would not work with the GCC runtime. For example, clang always generates
  559. /// the extended form of the class structure, and the extra fields are simply
  560. /// ignored by GCC libobjc.
  561. class CGObjCGCC : public CGObjCGNU {
  562. /// The GCC ABI message lookup function. Returns an IMP pointing to the
  563. /// method implementation for this message.
  564. LazyRuntimeFunction MsgLookupFn;
  565. /// The GCC ABI superclass message lookup function. Takes a pointer to a
  566. /// structure describing the receiver and the class, and a selector as
  567. /// arguments. Returns the IMP for the corresponding method.
  568. LazyRuntimeFunction MsgLookupSuperFn;
  569. protected:
  570. llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
  571. llvm::Value *cmd, llvm::MDNode *node,
  572. MessageSendInfo &MSI) override {
  573. CGBuilderTy &Builder = CGF.Builder;
  574. llvm::Value *args[] = {
  575. EnforceType(Builder, Receiver, IdTy),
  576. EnforceType(Builder, cmd, SelectorTy) };
  577. llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
  578. imp->setMetadata(msgSendMDKind, node);
  579. return imp.getInstruction();
  580. }
  581. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  582. llvm::Value *cmd, MessageSendInfo &MSI) override {
  583. CGBuilderTy &Builder = CGF.Builder;
  584. llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
  585. PtrToObjCSuperTy).getPointer(), cmd};
  586. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
  587. }
  588. public:
  589. CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
  590. // IMP objc_msg_lookup(id, SEL);
  591. MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
  592. nullptr);
  593. // IMP objc_msg_lookup_super(struct objc_super*, SEL);
  594. MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
  595. PtrToObjCSuperTy, SelectorTy, nullptr);
  596. }
  597. };
  598. /// Class used when targeting the new GNUstep runtime ABI.
  599. class CGObjCGNUstep : public CGObjCGNU {
  600. /// The slot lookup function. Returns a pointer to a cacheable structure
  601. /// that contains (among other things) the IMP.
  602. LazyRuntimeFunction SlotLookupFn;
  603. /// The GNUstep ABI superclass message lookup function. Takes a pointer to
  604. /// a structure describing the receiver and the class, and a selector as
  605. /// arguments. Returns the slot for the corresponding method. Superclass
  606. /// message lookup rarely changes, so this is a good caching opportunity.
  607. LazyRuntimeFunction SlotLookupSuperFn;
  608. /// Specialised function for setting atomic retain properties
  609. LazyRuntimeFunction SetPropertyAtomic;
  610. /// Specialised function for setting atomic copy properties
  611. LazyRuntimeFunction SetPropertyAtomicCopy;
  612. /// Specialised function for setting nonatomic retain properties
  613. LazyRuntimeFunction SetPropertyNonAtomic;
  614. /// Specialised function for setting nonatomic copy properties
  615. LazyRuntimeFunction SetPropertyNonAtomicCopy;
  616. /// Function to perform atomic copies of C++ objects with nontrivial copy
  617. /// constructors from Objective-C ivars.
  618. LazyRuntimeFunction CxxAtomicObjectGetFn;
  619. /// Function to perform atomic copies of C++ objects with nontrivial copy
  620. /// constructors to Objective-C ivars.
  621. LazyRuntimeFunction CxxAtomicObjectSetFn;
  622. /// Type of an slot structure pointer. This is returned by the various
  623. /// lookup functions.
  624. llvm::Type *SlotTy;
  625. public:
  626. llvm::Constant *GetEHType(QualType T) override;
  627. protected:
  628. llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
  629. llvm::Value *cmd, llvm::MDNode *node,
  630. MessageSendInfo &MSI) override {
  631. CGBuilderTy &Builder = CGF.Builder;
  632. llvm::Function *LookupFn = SlotLookupFn;
  633. // Store the receiver on the stack so that we can reload it later
  634. Address ReceiverPtr =
  635. CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
  636. Builder.CreateStore(Receiver, ReceiverPtr);
  637. llvm::Value *self;
  638. if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
  639. self = CGF.LoadObjCSelf();
  640. } else {
  641. self = llvm::ConstantPointerNull::get(IdTy);
  642. }
  643. // The lookup function is guaranteed not to capture the receiver pointer.
  644. LookupFn->setDoesNotCapture(1);
  645. llvm::Value *args[] = {
  646. EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
  647. EnforceType(Builder, cmd, SelectorTy),
  648. EnforceType(Builder, self, IdTy) };
  649. llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
  650. slot.setOnlyReadsMemory();
  651. slot->setMetadata(msgSendMDKind, node);
  652. // Load the imp from the slot
  653. llvm::Value *imp = Builder.CreateAlignedLoad(
  654. Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
  655. CGF.getPointerAlign());
  656. // The lookup function may have changed the receiver, so make sure we use
  657. // the new one.
  658. Receiver = Builder.CreateLoad(ReceiverPtr, true);
  659. return imp;
  660. }
  661. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  662. llvm::Value *cmd,
  663. MessageSendInfo &MSI) override {
  664. CGBuilderTy &Builder = CGF.Builder;
  665. llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
  666. llvm::CallInst *slot =
  667. CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
  668. slot->setOnlyReadsMemory();
  669. return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
  670. CGF.getPointerAlign());
  671. }
  672. public:
  673. CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
  674. const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
  675. llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
  676. PtrTy, PtrTy, IntTy, IMPTy, nullptr);
  677. SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
  678. // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
  679. SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
  680. SelectorTy, IdTy, nullptr);
  681. // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
  682. SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
  683. PtrToObjCSuperTy, SelectorTy, nullptr);
  684. // If we're in ObjC++ mode, then we want to make
  685. if (CGM.getLangOpts().CPlusPlus) {
  686. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  687. // void *__cxa_begin_catch(void *e)
  688. EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
  689. // void __cxa_end_catch(void)
  690. ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
  691. // void _Unwind_Resume_or_Rethrow(void*)
  692. ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
  693. PtrTy, nullptr);
  694. } else if (R.getVersion() >= VersionTuple(1, 7)) {
  695. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  696. // id objc_begin_catch(void *e)
  697. EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
  698. // void objc_end_catch(void)
  699. ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
  700. // void _Unwind_Resume_or_Rethrow(void*)
  701. ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
  702. PtrTy, nullptr);
  703. }
  704. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  705. SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
  706. SelectorTy, IdTy, PtrDiffTy, nullptr);
  707. SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
  708. IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
  709. SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
  710. IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
  711. SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
  712. VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
  713. // void objc_setCppObjectAtomic(void *dest, const void *src, void
  714. // *helper);
  715. CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
  716. PtrTy, PtrTy, nullptr);
  717. // void objc_getCppObjectAtomic(void *dest, const void *src, void
  718. // *helper);
  719. CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
  720. PtrTy, PtrTy, nullptr);
  721. }
  722. llvm::Constant *GetCppAtomicObjectGetFunction() override {
  723. // The optimised functions were added in version 1.7 of the GNUstep
  724. // runtime.
  725. assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
  726. VersionTuple(1, 7));
  727. return CxxAtomicObjectGetFn;
  728. }
  729. llvm::Constant *GetCppAtomicObjectSetFunction() override {
  730. // The optimised functions were added in version 1.7 of the GNUstep
  731. // runtime.
  732. assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
  733. VersionTuple(1, 7));
  734. return CxxAtomicObjectSetFn;
  735. }
  736. llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
  737. bool copy) override {
  738. // The optimised property functions omit the GC check, and so are not
  739. // safe to use in GC mode. The standard functions are fast in GC mode,
  740. // so there is less advantage in using them.
  741. assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
  742. // The optimised functions were added in version 1.7 of the GNUstep
  743. // runtime.
  744. assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
  745. VersionTuple(1, 7));
  746. if (atomic) {
  747. if (copy) return SetPropertyAtomicCopy;
  748. return SetPropertyAtomic;
  749. }
  750. return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
  751. }
  752. };
  753. /// Support for the ObjFW runtime.
  754. class CGObjCObjFW: public CGObjCGNU {
  755. protected:
  756. /// The GCC ABI message lookup function. Returns an IMP pointing to the
  757. /// method implementation for this message.
  758. LazyRuntimeFunction MsgLookupFn;
  759. /// stret lookup function. While this does not seem to make sense at the
  760. /// first look, this is required to call the correct forwarding function.
  761. LazyRuntimeFunction MsgLookupFnSRet;
  762. /// The GCC ABI superclass message lookup function. Takes a pointer to a
  763. /// structure describing the receiver and the class, and a selector as
  764. /// arguments. Returns the IMP for the corresponding method.
  765. LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
  766. llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
  767. llvm::Value *cmd, llvm::MDNode *node,
  768. MessageSendInfo &MSI) override {
  769. CGBuilderTy &Builder = CGF.Builder;
  770. llvm::Value *args[] = {
  771. EnforceType(Builder, Receiver, IdTy),
  772. EnforceType(Builder, cmd, SelectorTy) };
  773. llvm::CallSite imp;
  774. if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
  775. imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
  776. else
  777. imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
  778. imp->setMetadata(msgSendMDKind, node);
  779. return imp.getInstruction();
  780. }
  781. llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
  782. llvm::Value *cmd, MessageSendInfo &MSI) override {
  783. CGBuilderTy &Builder = CGF.Builder;
  784. llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper.getPointer(),
  785. PtrToObjCSuperTy), cmd};
  786. if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
  787. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
  788. else
  789. return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
  790. }
  791. llvm::Value *GetClassNamed(CodeGenFunction &CGF,
  792. const std::string &Name, bool isWeak) override {
  793. if (isWeak)
  794. return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
  795. EmitClassRef(Name);
  796. std::string SymbolName = "_OBJC_CLASS_" + Name;
  797. llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
  798. if (!ClassSymbol)
  799. ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
  800. llvm::GlobalValue::ExternalLinkage,
  801. nullptr, SymbolName);
  802. return ClassSymbol;
  803. }
  804. public:
  805. CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
  806. // IMP objc_msg_lookup(id, SEL);
  807. MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
  808. MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
  809. SelectorTy, nullptr);
  810. // IMP objc_msg_lookup_super(struct objc_super*, SEL);
  811. MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
  812. PtrToObjCSuperTy, SelectorTy, nullptr);
  813. MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
  814. PtrToObjCSuperTy, SelectorTy, nullptr);
  815. }
  816. };
  817. } // end anonymous namespace
  818. /// Emits a reference to a dummy variable which is emitted with each class.
  819. /// This ensures that a linker error will be generated when trying to link
  820. /// together modules where a referenced class is not defined.
  821. void CGObjCGNU::EmitClassRef(const std::string &className) {
  822. std::string symbolRef = "__objc_class_ref_" + className;
  823. // Don't emit two copies of the same symbol
  824. if (TheModule.getGlobalVariable(symbolRef))
  825. return;
  826. std::string symbolName = "__objc_class_name_" + className;
  827. llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
  828. if (!ClassSymbol) {
  829. ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
  830. llvm::GlobalValue::ExternalLinkage,
  831. nullptr, symbolName);
  832. }
  833. new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
  834. llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
  835. }
  836. static std::string SymbolNameForMethod( StringRef ClassName,
  837. StringRef CategoryName, const Selector MethodName,
  838. bool isClassMethod) {
  839. std::string MethodNameColonStripped = MethodName.getAsString();
  840. std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
  841. ':', '_');
  842. return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
  843. CategoryName + "_" + MethodNameColonStripped).str();
  844. }
  845. CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
  846. unsigned protocolClassVersion)
  847. : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
  848. VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
  849. MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
  850. ProtocolVersion(protocolClassVersion) {
  851. msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
  852. CodeGenTypes &Types = CGM.getTypes();
  853. IntTy = cast<llvm::IntegerType>(
  854. Types.ConvertType(CGM.getContext().IntTy));
  855. LongTy = cast<llvm::IntegerType>(
  856. Types.ConvertType(CGM.getContext().LongTy));
  857. SizeTy = cast<llvm::IntegerType>(
  858. Types.ConvertType(CGM.getContext().getSizeType()));
  859. PtrDiffTy = cast<llvm::IntegerType>(
  860. Types.ConvertType(CGM.getContext().getPointerDiffType()));
  861. BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
  862. Int8Ty = llvm::Type::getInt8Ty(VMContext);
  863. // C string type. Used in lots of places.
  864. PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
  865. Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
  866. Zeros[1] = Zeros[0];
  867. NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
  868. // Get the selector Type.
  869. QualType selTy = CGM.getContext().getObjCSelType();
  870. if (QualType() == selTy) {
  871. SelectorTy = PtrToInt8Ty;
  872. } else {
  873. SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
  874. }
  875. PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
  876. PtrTy = PtrToInt8Ty;
  877. Int32Ty = llvm::Type::getInt32Ty(VMContext);
  878. Int64Ty = llvm::Type::getInt64Ty(VMContext);
  879. IntPtrTy =
  880. CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
  881. // Object type
  882. QualType UnqualIdTy = CGM.getContext().getObjCIdType();
  883. ASTIdTy = CanQualType();
  884. if (UnqualIdTy != QualType()) {
  885. ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
  886. IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
  887. } else {
  888. IdTy = PtrToInt8Ty;
  889. }
  890. PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
  891. ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
  892. PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
  893. llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
  894. // void objc_exception_throw(id);
  895. ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
  896. ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
  897. // int objc_sync_enter(id);
  898. SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
  899. // int objc_sync_exit(id);
  900. SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
  901. // void objc_enumerationMutation (id)
  902. EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
  903. IdTy, nullptr);
  904. // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
  905. GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
  906. PtrDiffTy, BoolTy, nullptr);
  907. // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
  908. SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
  909. PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
  910. // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
  911. GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
  912. PtrDiffTy, BoolTy, BoolTy, nullptr);
  913. // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
  914. SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
  915. PtrDiffTy, BoolTy, BoolTy, nullptr);
  916. // IMP type
  917. llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
  918. IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
  919. true));
  920. const LangOptions &Opts = CGM.getLangOpts();
  921. if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
  922. RuntimeVersion = 10;
  923. // Don't bother initialising the GC stuff unless we're compiling in GC mode
  924. if (Opts.getGC() != LangOptions::NonGC) {
  925. // This is a bit of an hack. We should sort this out by having a proper
  926. // CGObjCGNUstep subclass for GC, but we may want to really support the old
  927. // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
  928. // Get selectors needed in GC mode
  929. RetainSel = GetNullarySelector("retain", CGM.getContext());
  930. ReleaseSel = GetNullarySelector("release", CGM.getContext());
  931. AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
  932. // Get functions needed in GC mode
  933. // id objc_assign_ivar(id, id, ptrdiff_t);
  934. IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
  935. nullptr);
  936. // id objc_assign_strongCast (id, id*)
  937. StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
  938. PtrToIdTy, nullptr);
  939. // id objc_assign_global(id, id*);
  940. GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
  941. nullptr);
  942. // id objc_assign_weak(id, id*);
  943. WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
  944. // id objc_read_weak(id*);
  945. WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
  946. // void *objc_memmove_collectable(void*, void *, size_t);
  947. MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
  948. SizeTy, nullptr);
  949. }
  950. }
  951. llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
  952. const std::string &Name,
  953. bool isWeak) {
  954. llvm::Constant *ClassName = MakeConstantString(Name);
  955. // With the incompatible ABI, this will need to be replaced with a direct
  956. // reference to the class symbol. For the compatible nonfragile ABI we are
  957. // still performing this lookup at run time but emitting the symbol for the
  958. // class externally so that we can make the switch later.
  959. //
  960. // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
  961. // with memoized versions or with static references if it's safe to do so.
  962. if (!isWeak)
  963. EmitClassRef(Name);
  964. llvm::Constant *ClassLookupFn =
  965. CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
  966. "objc_lookup_class");
  967. return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
  968. }
  969. // This has to perform the lookup every time, since posing and related
  970. // techniques can modify the name -> class mapping.
  971. llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
  972. const ObjCInterfaceDecl *OID) {
  973. return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
  974. }
  975. llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
  976. return GetClassNamed(CGF, "NSAutoreleasePool", false);
  977. }
  978. llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
  979. const std::string &TypeEncoding) {
  980. SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
  981. llvm::GlobalAlias *SelValue = nullptr;
  982. for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
  983. e = Types.end() ; i!=e ; i++) {
  984. if (i->first == TypeEncoding) {
  985. SelValue = i->second;
  986. break;
  987. }
  988. }
  989. if (!SelValue) {
  990. SelValue = llvm::GlobalAlias::create(
  991. SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
  992. ".objc_selector_" + Sel.getAsString(), &TheModule);
  993. Types.emplace_back(TypeEncoding, SelValue);
  994. }
  995. return SelValue;
  996. }
  997. Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
  998. llvm::Value *SelValue = GetSelector(CGF, Sel);
  999. // Store it to a temporary. Does this satisfy the semantics of
  1000. // GetAddrOfSelector? Hopefully.
  1001. Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
  1002. CGF.getPointerAlign());
  1003. CGF.Builder.CreateStore(SelValue, tmp);
  1004. return tmp;
  1005. }
  1006. llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
  1007. return GetSelector(CGF, Sel, std::string());
  1008. }
  1009. llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
  1010. const ObjCMethodDecl *Method) {
  1011. std::string SelTypes;
  1012. CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
  1013. return GetSelector(CGF, Method->getSelector(), SelTypes);
  1014. }
  1015. llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
  1016. if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
  1017. // With the old ABI, there was only one kind of catchall, which broke
  1018. // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
  1019. // a pointer indicating object catchalls, and NULL to indicate real
  1020. // catchalls
  1021. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  1022. return MakeConstantString("@id");
  1023. } else {
  1024. return nullptr;
  1025. }
  1026. }
  1027. // All other types should be Objective-C interface pointer types.
  1028. const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
  1029. assert(OPT && "Invalid @catch type.");
  1030. const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
  1031. assert(IDecl && "Invalid @catch type.");
  1032. return MakeConstantString(IDecl->getIdentifier()->getName());
  1033. }
  1034. llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
  1035. if (!CGM.getLangOpts().CPlusPlus)
  1036. return CGObjCGNU::GetEHType(T);
  1037. // For Objective-C++, we want to provide the ability to catch both C++ and
  1038. // Objective-C objects in the same function.
  1039. // There's a particular fixed type info for 'id'.
  1040. if (T->isObjCIdType() ||
  1041. T->isObjCQualifiedIdType()) {
  1042. llvm::Constant *IDEHType =
  1043. CGM.getModule().getGlobalVariable("__objc_id_type_info");
  1044. if (!IDEHType)
  1045. IDEHType =
  1046. new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
  1047. false,
  1048. llvm::GlobalValue::ExternalLinkage,
  1049. nullptr, "__objc_id_type_info");
  1050. return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
  1051. }
  1052. const ObjCObjectPointerType *PT =
  1053. T->getAs<ObjCObjectPointerType>();
  1054. assert(PT && "Invalid @catch type.");
  1055. const ObjCInterfaceType *IT = PT->getInterfaceType();
  1056. assert(IT && "Invalid @catch type.");
  1057. std::string className = IT->getDecl()->getIdentifier()->getName();
  1058. std::string typeinfoName = "__objc_eh_typeinfo_" + className;
  1059. // Return the existing typeinfo if it exists
  1060. llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
  1061. if (typeinfo)
  1062. return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
  1063. // Otherwise create it.
  1064. // vtable for gnustep::libobjc::__objc_class_type_info
  1065. // It's quite ugly hard-coding this. Ideally we'd generate it using the host
  1066. // platform's name mangling.
  1067. const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
  1068. auto *Vtable = TheModule.getGlobalVariable(vtableName);
  1069. if (!Vtable) {
  1070. Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
  1071. llvm::GlobalValue::ExternalLinkage,
  1072. nullptr, vtableName);
  1073. }
  1074. llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
  1075. auto *BVtable = llvm::ConstantExpr::getBitCast(
  1076. llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
  1077. PtrToInt8Ty);
  1078. llvm::Constant *typeName =
  1079. ExportUniqueString(className, "__objc_eh_typename_");
  1080. std::vector<llvm::Constant*> fields;
  1081. fields.push_back(BVtable);
  1082. fields.push_back(typeName);
  1083. llvm::Constant *TI =
  1084. MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr),
  1085. fields, CGM.getPointerAlign(),
  1086. "__objc_eh_typeinfo_" + className,
  1087. llvm::GlobalValue::LinkOnceODRLinkage);
  1088. return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
  1089. }
  1090. /// Generate an NSConstantString object.
  1091. ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
  1092. std::string Str = SL->getString().str();
  1093. CharUnits Align = CGM.getPointerAlign();
  1094. // Look for an existing one
  1095. llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
  1096. if (old != ObjCStrings.end())
  1097. return ConstantAddress(old->getValue(), Align);
  1098. StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
  1099. if (StringClass.empty()) StringClass = "NXConstantString";
  1100. std::string Sym = "_OBJC_CLASS_";
  1101. Sym += StringClass;
  1102. llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
  1103. if (!isa)
  1104. isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
  1105. llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
  1106. else if (isa->getType() != PtrToIdTy)
  1107. isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
  1108. std::vector<llvm::Constant*> Ivars;
  1109. Ivars.push_back(isa);
  1110. Ivars.push_back(MakeConstantString(Str));
  1111. Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
  1112. llvm::Constant *ObjCStr = MakeGlobal(
  1113. llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, nullptr),
  1114. Ivars, Align, ".objc_str");
  1115. ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
  1116. ObjCStrings[Str] = ObjCStr;
  1117. ConstantStrings.push_back(ObjCStr);
  1118. return ConstantAddress(ObjCStr, Align);
  1119. }
  1120. ///Generates a message send where the super is the receiver. This is a message
  1121. ///send to self with special delivery semantics indicating which class's method
  1122. ///should be called.
  1123. RValue
  1124. CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
  1125. ReturnValueSlot Return,
  1126. QualType ResultType,
  1127. Selector Sel,
  1128. const ObjCInterfaceDecl *Class,
  1129. bool isCategoryImpl,
  1130. llvm::Value *Receiver,
  1131. bool IsClassMessage,
  1132. const CallArgList &CallArgs,
  1133. const ObjCMethodDecl *Method) {
  1134. CGBuilderTy &Builder = CGF.Builder;
  1135. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
  1136. if (Sel == RetainSel || Sel == AutoreleaseSel) {
  1137. return RValue::get(EnforceType(Builder, Receiver,
  1138. CGM.getTypes().ConvertType(ResultType)));
  1139. }
  1140. if (Sel == ReleaseSel) {
  1141. return RValue::get(nullptr);
  1142. }
  1143. }
  1144. llvm::Value *cmd = GetSelector(CGF, Sel);
  1145. CallArgList ActualArgs;
  1146. ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
  1147. ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
  1148. ActualArgs.addFrom(CallArgs);
  1149. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  1150. llvm::Value *ReceiverClass = nullptr;
  1151. if (isCategoryImpl) {
  1152. llvm::Constant *classLookupFunction = nullptr;
  1153. if (IsClassMessage) {
  1154. classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
  1155. IdTy, PtrTy, true), "objc_get_meta_class");
  1156. } else {
  1157. classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
  1158. IdTy, PtrTy, true), "objc_get_class");
  1159. }
  1160. ReceiverClass = Builder.CreateCall(classLookupFunction,
  1161. MakeConstantString(Class->getNameAsString()));
  1162. } else {
  1163. // Set up global aliases for the metaclass or class pointer if they do not
  1164. // already exist. These will are forward-references which will be set to
  1165. // pointers to the class and metaclass structure created for the runtime
  1166. // load function. To send a message to super, we look up the value of the
  1167. // super_class pointer from either the class or metaclass structure.
  1168. if (IsClassMessage) {
  1169. if (!MetaClassPtrAlias) {
  1170. MetaClassPtrAlias = llvm::GlobalAlias::create(
  1171. IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
  1172. ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
  1173. }
  1174. ReceiverClass = MetaClassPtrAlias;
  1175. } else {
  1176. if (!ClassPtrAlias) {
  1177. ClassPtrAlias = llvm::GlobalAlias::create(
  1178. IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
  1179. ".objc_class_ref" + Class->getNameAsString(), &TheModule);
  1180. }
  1181. ReceiverClass = ClassPtrAlias;
  1182. }
  1183. }
  1184. // Cast the pointer to a simplified version of the class structure
  1185. llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr);
  1186. ReceiverClass = Builder.CreateBitCast(ReceiverClass,
  1187. llvm::PointerType::getUnqual(CastTy));
  1188. // Get the superclass pointer
  1189. ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
  1190. // Load the superclass pointer
  1191. ReceiverClass =
  1192. Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
  1193. // Construct the structure used to look up the IMP
  1194. llvm::StructType *ObjCSuperTy = llvm::StructType::get(
  1195. Receiver->getType(), IdTy, nullptr);
  1196. // FIXME: Is this really supposed to be a dynamic alloca?
  1197. Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
  1198. CGF.getPointerAlign());
  1199. Builder.CreateStore(Receiver,
  1200. Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
  1201. Builder.CreateStore(ReceiverClass,
  1202. Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
  1203. ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
  1204. // Get the IMP
  1205. llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
  1206. imp = EnforceType(Builder, imp, MSI.MessengerType);
  1207. llvm::Metadata *impMD[] = {
  1208. llvm::MDString::get(VMContext, Sel.getAsString()),
  1209. llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
  1210. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  1211. llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
  1212. llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
  1213. llvm::Instruction *call;
  1214. RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
  1215. CGCalleeInfo(), &call);
  1216. call->setMetadata(msgSendMDKind, node);
  1217. return msgRet;
  1218. }
  1219. /// Generate code for a message send expression.
  1220. RValue
  1221. CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
  1222. ReturnValueSlot Return,
  1223. QualType ResultType,
  1224. Selector Sel,
  1225. llvm::Value *Receiver,
  1226. const CallArgList &CallArgs,
  1227. const ObjCInterfaceDecl *Class,
  1228. const ObjCMethodDecl *Method) {
  1229. CGBuilderTy &Builder = CGF.Builder;
  1230. // Strip out message sends to retain / release in GC mode
  1231. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
  1232. if (Sel == RetainSel || Sel == AutoreleaseSel) {
  1233. return RValue::get(EnforceType(Builder, Receiver,
  1234. CGM.getTypes().ConvertType(ResultType)));
  1235. }
  1236. if (Sel == ReleaseSel) {
  1237. return RValue::get(nullptr);
  1238. }
  1239. }
  1240. // If the return type is something that goes in an integer register, the
  1241. // runtime will handle 0 returns. For other cases, we fill in the 0 value
  1242. // ourselves.
  1243. //
  1244. // The language spec says the result of this kind of message send is
  1245. // undefined, but lots of people seem to have forgotten to read that
  1246. // paragraph and insist on sending messages to nil that have structure
  1247. // returns. With GCC, this generates a random return value (whatever happens
  1248. // to be on the stack / in those registers at the time) on most platforms,
  1249. // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
  1250. // the stack.
  1251. bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
  1252. ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
  1253. llvm::BasicBlock *startBB = nullptr;
  1254. llvm::BasicBlock *messageBB = nullptr;
  1255. llvm::BasicBlock *continueBB = nullptr;
  1256. if (!isPointerSizedReturn) {
  1257. startBB = Builder.GetInsertBlock();
  1258. messageBB = CGF.createBasicBlock("msgSend");
  1259. continueBB = CGF.createBasicBlock("continue");
  1260. llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
  1261. llvm::Constant::getNullValue(Receiver->getType()));
  1262. Builder.CreateCondBr(isNil, continueBB, messageBB);
  1263. CGF.EmitBlock(messageBB);
  1264. }
  1265. IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
  1266. llvm::Value *cmd;
  1267. if (Method)
  1268. cmd = GetSelector(CGF, Method);
  1269. else
  1270. cmd = GetSelector(CGF, Sel);
  1271. cmd = EnforceType(Builder, cmd, SelectorTy);
  1272. Receiver = EnforceType(Builder, Receiver, IdTy);
  1273. llvm::Metadata *impMD[] = {
  1274. llvm::MDString::get(VMContext, Sel.getAsString()),
  1275. llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
  1276. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  1277. llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
  1278. llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
  1279. CallArgList ActualArgs;
  1280. ActualArgs.add(RValue::get(Receiver), ASTIdTy);
  1281. ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
  1282. ActualArgs.addFrom(CallArgs);
  1283. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  1284. // Get the IMP to call
  1285. llvm::Value *imp;
  1286. // If we have non-legacy dispatch specified, we try using the objc_msgSend()
  1287. // functions. These are not supported on all platforms (or all runtimes on a
  1288. // given platform), so we
  1289. switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
  1290. case CodeGenOptions::Legacy:
  1291. imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
  1292. break;
  1293. case CodeGenOptions::Mixed:
  1294. case CodeGenOptions::NonLegacy:
  1295. if (CGM.ReturnTypeUsesFPRet(ResultType)) {
  1296. imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  1297. "objc_msgSend_fpret");
  1298. } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
  1299. // The actual types here don't matter - we're going to bitcast the
  1300. // function anyway
  1301. imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  1302. "objc_msgSend_stret");
  1303. } else {
  1304. imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
  1305. "objc_msgSend");
  1306. }
  1307. }
  1308. // Reset the receiver in case the lookup modified it
  1309. ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
  1310. imp = EnforceType(Builder, imp, MSI.MessengerType);
  1311. llvm::Instruction *call;
  1312. RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
  1313. CGCalleeInfo(), &call);
  1314. call->setMetadata(msgSendMDKind, node);
  1315. if (!isPointerSizedReturn) {
  1316. messageBB = CGF.Builder.GetInsertBlock();
  1317. CGF.Builder.CreateBr(continueBB);
  1318. CGF.EmitBlock(continueBB);
  1319. if (msgRet.isScalar()) {
  1320. llvm::Value *v = msgRet.getScalarVal();
  1321. llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
  1322. phi->addIncoming(v, messageBB);
  1323. phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
  1324. msgRet = RValue::get(phi);
  1325. } else if (msgRet.isAggregate()) {
  1326. Address v = msgRet.getAggregateAddress();
  1327. llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
  1328. llvm::Type *RetTy = v.getElementType();
  1329. Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
  1330. CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
  1331. phi->addIncoming(v.getPointer(), messageBB);
  1332. phi->addIncoming(NullVal.getPointer(), startBB);
  1333. msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
  1334. } else /* isComplex() */ {
  1335. std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
  1336. llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
  1337. phi->addIncoming(v.first, messageBB);
  1338. phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
  1339. startBB);
  1340. llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
  1341. phi2->addIncoming(v.second, messageBB);
  1342. phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
  1343. startBB);
  1344. msgRet = RValue::getComplex(phi, phi2);
  1345. }
  1346. }
  1347. return msgRet;
  1348. }
  1349. /// Generates a MethodList. Used in construction of a objc_class and
  1350. /// objc_category structures.
  1351. llvm::Constant *CGObjCGNU::
  1352. GenerateMethodList(StringRef ClassName,
  1353. StringRef CategoryName,
  1354. ArrayRef<Selector> MethodSels,
  1355. ArrayRef<llvm::Constant *> MethodTypes,
  1356. bool isClassMethodList) {
  1357. if (MethodSels.empty())
  1358. return NULLPtr;
  1359. // Get the method structure type.
  1360. llvm::StructType *ObjCMethodTy = llvm::StructType::get(
  1361. PtrToInt8Ty, // Really a selector, but the runtime creates it us.
  1362. PtrToInt8Ty, // Method types
  1363. IMPTy, //Method pointer
  1364. nullptr);
  1365. std::vector<llvm::Constant*> Methods;
  1366. std::vector<llvm::Constant*> Elements;
  1367. for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
  1368. Elements.clear();
  1369. llvm::Constant *Method =
  1370. TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
  1371. MethodSels[i],
  1372. isClassMethodList));
  1373. assert(Method && "Can't generate metadata for method that doesn't exist");
  1374. llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
  1375. Elements.push_back(C);
  1376. Elements.push_back(MethodTypes[i]);
  1377. Method = llvm::ConstantExpr::getBitCast(Method,
  1378. IMPTy);
  1379. Elements.push_back(Method);
  1380. Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
  1381. }
  1382. // Array of method structures
  1383. llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
  1384. Methods.size());
  1385. llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
  1386. Methods);
  1387. // Structure containing list pointer, array and array count
  1388. llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
  1389. llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
  1390. ObjCMethodListTy->setBody(
  1391. NextPtrTy,
  1392. IntTy,
  1393. ObjCMethodArrayTy,
  1394. nullptr);
  1395. Methods.clear();
  1396. Methods.push_back(llvm::ConstantPointerNull::get(
  1397. llvm::PointerType::getUnqual(ObjCMethodListTy)));
  1398. Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
  1399. Methods.push_back(MethodArray);
  1400. // Create an instance of the structure
  1401. return MakeGlobal(ObjCMethodListTy, Methods, CGM.getPointerAlign(),
  1402. ".objc_method_list");
  1403. }
  1404. /// Generates an IvarList. Used in construction of a objc_class.
  1405. llvm::Constant *CGObjCGNU::
  1406. GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
  1407. ArrayRef<llvm::Constant *> IvarTypes,
  1408. ArrayRef<llvm::Constant *> IvarOffsets) {
  1409. if (IvarNames.size() == 0)
  1410. return NULLPtr;
  1411. // Get the method structure type.
  1412. llvm::StructType *ObjCIvarTy = llvm::StructType::get(
  1413. PtrToInt8Ty,
  1414. PtrToInt8Ty,
  1415. IntTy,
  1416. nullptr);
  1417. std::vector<llvm::Constant*> Ivars;
  1418. std::vector<llvm::Constant*> Elements;
  1419. for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
  1420. Elements.clear();
  1421. Elements.push_back(IvarNames[i]);
  1422. Elements.push_back(IvarTypes[i]);
  1423. Elements.push_back(IvarOffsets[i]);
  1424. Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
  1425. }
  1426. // Array of method structures
  1427. llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
  1428. IvarNames.size());
  1429. Elements.clear();
  1430. Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
  1431. Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
  1432. // Structure containing array and array count
  1433. llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
  1434. ObjCIvarArrayTy,
  1435. nullptr);
  1436. // Create an instance of the structure
  1437. return MakeGlobal(ObjCIvarListTy, Elements, CGM.getPointerAlign(),
  1438. ".objc_ivar_list");
  1439. }
  1440. /// Generate a class structure
  1441. llvm::Constant *CGObjCGNU::GenerateClassStructure(
  1442. llvm::Constant *MetaClass,
  1443. llvm::Constant *SuperClass,
  1444. unsigned info,
  1445. const char *Name,
  1446. llvm::Constant *Version,
  1447. llvm::Constant *InstanceSize,
  1448. llvm::Constant *IVars,
  1449. llvm::Constant *Methods,
  1450. llvm::Constant *Protocols,
  1451. llvm::Constant *IvarOffsets,
  1452. llvm::Constant *Properties,
  1453. llvm::Constant *StrongIvarBitmap,
  1454. llvm::Constant *WeakIvarBitmap,
  1455. bool isMeta) {
  1456. // Set up the class structure
  1457. // Note: Several of these are char*s when they should be ids. This is
  1458. // because the runtime performs this translation on load.
  1459. //
  1460. // Fields marked New ABI are part of the GNUstep runtime. We emit them
  1461. // anyway; the classes will still work with the GNU runtime, they will just
  1462. // be ignored.
  1463. llvm::StructType *ClassTy = llvm::StructType::get(
  1464. PtrToInt8Ty, // isa
  1465. PtrToInt8Ty, // super_class
  1466. PtrToInt8Ty, // name
  1467. LongTy, // version
  1468. LongTy, // info
  1469. LongTy, // instance_size
  1470. IVars->getType(), // ivars
  1471. Methods->getType(), // methods
  1472. // These are all filled in by the runtime, so we pretend
  1473. PtrTy, // dtable
  1474. PtrTy, // subclass_list
  1475. PtrTy, // sibling_class
  1476. PtrTy, // protocols
  1477. PtrTy, // gc_object_type
  1478. // New ABI:
  1479. LongTy, // abi_version
  1480. IvarOffsets->getType(), // ivar_offsets
  1481. Properties->getType(), // properties
  1482. IntPtrTy, // strong_pointers
  1483. IntPtrTy, // weak_pointers
  1484. nullptr);
  1485. llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
  1486. // Fill in the structure
  1487. std::vector<llvm::Constant*> Elements;
  1488. Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
  1489. Elements.push_back(SuperClass);
  1490. Elements.push_back(MakeConstantString(Name, ".class_name"));
  1491. Elements.push_back(Zero);
  1492. Elements.push_back(llvm::ConstantInt::get(LongTy, info));
  1493. if (isMeta) {
  1494. llvm::DataLayout td(&TheModule);
  1495. Elements.push_back(
  1496. llvm::ConstantInt::get(LongTy,
  1497. td.getTypeSizeInBits(ClassTy) /
  1498. CGM.getContext().getCharWidth()));
  1499. } else
  1500. Elements.push_back(InstanceSize);
  1501. Elements.push_back(IVars);
  1502. Elements.push_back(Methods);
  1503. Elements.push_back(NULLPtr);
  1504. Elements.push_back(NULLPtr);
  1505. Elements.push_back(NULLPtr);
  1506. Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
  1507. Elements.push_back(NULLPtr);
  1508. Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
  1509. Elements.push_back(IvarOffsets);
  1510. Elements.push_back(Properties);
  1511. Elements.push_back(StrongIvarBitmap);
  1512. Elements.push_back(WeakIvarBitmap);
  1513. // Create an instance of the structure
  1514. // This is now an externally visible symbol, so that we can speed up class
  1515. // messages in the next ABI. We may already have some weak references to
  1516. // this, so check and fix them properly.
  1517. std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
  1518. std::string(Name));
  1519. llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
  1520. llvm::Constant *Class =
  1521. MakeGlobal(ClassTy, Elements, CGM.getPointerAlign(), ClassSym,
  1522. llvm::GlobalValue::ExternalLinkage);
  1523. if (ClassRef) {
  1524. ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
  1525. ClassRef->getType()));
  1526. ClassRef->removeFromParent();
  1527. Class->setName(ClassSym);
  1528. }
  1529. return Class;
  1530. }
  1531. llvm::Constant *CGObjCGNU::
  1532. GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
  1533. ArrayRef<llvm::Constant *> MethodTypes) {
  1534. // Get the method structure type.
  1535. llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
  1536. PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
  1537. PtrToInt8Ty,
  1538. nullptr);
  1539. std::vector<llvm::Constant*> Methods;
  1540. std::vector<llvm::Constant*> Elements;
  1541. for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
  1542. Elements.clear();
  1543. Elements.push_back(MethodNames[i]);
  1544. Elements.push_back(MethodTypes[i]);
  1545. Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
  1546. }
  1547. llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
  1548. MethodNames.size());
  1549. llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
  1550. Methods);
  1551. llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
  1552. IntTy, ObjCMethodArrayTy, nullptr);
  1553. Methods.clear();
  1554. Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
  1555. Methods.push_back(Array);
  1556. return MakeGlobal(ObjCMethodDescListTy, Methods, CGM.getPointerAlign(),
  1557. ".objc_method_list");
  1558. }
  1559. // Create the protocol list structure used in classes, categories and so on
  1560. llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
  1561. llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
  1562. Protocols.size());
  1563. llvm::StructType *ProtocolListTy = llvm::StructType::get(
  1564. PtrTy, //Should be a recurisve pointer, but it's always NULL here.
  1565. SizeTy,
  1566. ProtocolArrayTy,
  1567. nullptr);
  1568. std::vector<llvm::Constant*> Elements;
  1569. for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
  1570. iter != endIter ; iter++) {
  1571. llvm::Constant *protocol = nullptr;
  1572. llvm::StringMap<llvm::Constant*>::iterator value =
  1573. ExistingProtocols.find(*iter);
  1574. if (value == ExistingProtocols.end()) {
  1575. protocol = GenerateEmptyProtocol(*iter);
  1576. } else {
  1577. protocol = value->getValue();
  1578. }
  1579. llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
  1580. PtrToInt8Ty);
  1581. Elements.push_back(Ptr);
  1582. }
  1583. llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
  1584. Elements);
  1585. Elements.clear();
  1586. Elements.push_back(NULLPtr);
  1587. Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
  1588. Elements.push_back(ProtocolArray);
  1589. return MakeGlobal(ProtocolListTy, Elements, CGM.getPointerAlign(),
  1590. ".objc_protocol_list");
  1591. }
  1592. llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
  1593. const ObjCProtocolDecl *PD) {
  1594. llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
  1595. llvm::Type *T =
  1596. CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
  1597. return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
  1598. }
  1599. llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
  1600. const std::string &ProtocolName) {
  1601. SmallVector<std::string, 0> EmptyStringVector;
  1602. SmallVector<llvm::Constant*, 0> EmptyConstantVector;
  1603. llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
  1604. llvm::Constant *MethodList =
  1605. GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
  1606. // Protocols are objects containing lists of the methods implemented and
  1607. // protocols adopted.
  1608. llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
  1609. PtrToInt8Ty,
  1610. ProtocolList->getType(),
  1611. MethodList->getType(),
  1612. MethodList->getType(),
  1613. MethodList->getType(),
  1614. MethodList->getType(),
  1615. nullptr);
  1616. std::vector<llvm::Constant*> Elements;
  1617. // The isa pointer must be set to a magic number so the runtime knows it's
  1618. // the correct layout.
  1619. Elements.push_back(llvm::ConstantExpr::getIntToPtr(
  1620. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  1621. Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
  1622. Elements.push_back(ProtocolList);
  1623. Elements.push_back(MethodList);
  1624. Elements.push_back(MethodList);
  1625. Elements.push_back(MethodList);
  1626. Elements.push_back(MethodList);
  1627. return MakeGlobal(ProtocolTy, Elements, CGM.getPointerAlign(),
  1628. ".objc_protocol");
  1629. }
  1630. void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
  1631. ASTContext &Context = CGM.getContext();
  1632. std::string ProtocolName = PD->getNameAsString();
  1633. // Use the protocol definition, if there is one.
  1634. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  1635. PD = Def;
  1636. SmallVector<std::string, 16> Protocols;
  1637. for (const auto *PI : PD->protocols())
  1638. Protocols.push_back(PI->getNameAsString());
  1639. SmallVector<llvm::Constant*, 16> InstanceMethodNames;
  1640. SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
  1641. SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
  1642. SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
  1643. for (const auto *I : PD->instance_methods()) {
  1644. std::string TypeStr;
  1645. Context.getObjCEncodingForMethodDecl(I, TypeStr);
  1646. if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
  1647. OptionalInstanceMethodNames.push_back(
  1648. MakeConstantString(I->getSelector().getAsString()));
  1649. OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
  1650. } else {
  1651. InstanceMethodNames.push_back(
  1652. MakeConstantString(I->getSelector().getAsString()));
  1653. InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
  1654. }
  1655. }
  1656. // Collect information about class methods:
  1657. SmallVector<llvm::Constant*, 16> ClassMethodNames;
  1658. SmallVector<llvm::Constant*, 16> ClassMethodTypes;
  1659. SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
  1660. SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
  1661. for (const auto *I : PD->class_methods()) {
  1662. std::string TypeStr;
  1663. Context.getObjCEncodingForMethodDecl(I,TypeStr);
  1664. if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
  1665. OptionalClassMethodNames.push_back(
  1666. MakeConstantString(I->getSelector().getAsString()));
  1667. OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
  1668. } else {
  1669. ClassMethodNames.push_back(
  1670. MakeConstantString(I->getSelector().getAsString()));
  1671. ClassMethodTypes.push_back(MakeConstantString(TypeStr));
  1672. }
  1673. }
  1674. llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
  1675. llvm::Constant *InstanceMethodList =
  1676. GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
  1677. llvm::Constant *ClassMethodList =
  1678. GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
  1679. llvm::Constant *OptionalInstanceMethodList =
  1680. GenerateProtocolMethodList(OptionalInstanceMethodNames,
  1681. OptionalInstanceMethodTypes);
  1682. llvm::Constant *OptionalClassMethodList =
  1683. GenerateProtocolMethodList(OptionalClassMethodNames,
  1684. OptionalClassMethodTypes);
  1685. // Property metadata: name, attributes, isSynthesized, setter name, setter
  1686. // types, getter name, getter types.
  1687. // The isSynthesized value is always set to 0 in a protocol. It exists to
  1688. // simplify the runtime library by allowing it to use the same data
  1689. // structures for protocol metadata everywhere.
  1690. llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
  1691. PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
  1692. PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
  1693. std::vector<llvm::Constant*> Properties;
  1694. std::vector<llvm::Constant*> OptionalProperties;
  1695. // Add all of the property methods need adding to the method list and to the
  1696. // property metadata list.
  1697. for (auto *property : PD->instance_properties()) {
  1698. std::vector<llvm::Constant*> Fields;
  1699. Fields.push_back(MakePropertyEncodingString(property, nullptr));
  1700. PushPropertyAttributes(Fields, property);
  1701. if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
  1702. std::string TypeStr;
  1703. Context.getObjCEncodingForMethodDecl(getter,TypeStr);
  1704. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  1705. InstanceMethodTypes.push_back(TypeEncoding);
  1706. Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
  1707. Fields.push_back(TypeEncoding);
  1708. } else {
  1709. Fields.push_back(NULLPtr);
  1710. Fields.push_back(NULLPtr);
  1711. }
  1712. if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
  1713. std::string TypeStr;
  1714. Context.getObjCEncodingForMethodDecl(setter,TypeStr);
  1715. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  1716. InstanceMethodTypes.push_back(TypeEncoding);
  1717. Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
  1718. Fields.push_back(TypeEncoding);
  1719. } else {
  1720. Fields.push_back(NULLPtr);
  1721. Fields.push_back(NULLPtr);
  1722. }
  1723. if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
  1724. OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
  1725. } else {
  1726. Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
  1727. }
  1728. }
  1729. llvm::Constant *PropertyArray = llvm::ConstantArray::get(
  1730. llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
  1731. llvm::Constant* PropertyListInitFields[] =
  1732. {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
  1733. llvm::Constant *PropertyListInit =
  1734. llvm::ConstantStruct::getAnon(PropertyListInitFields);
  1735. llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
  1736. PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
  1737. PropertyListInit, ".objc_property_list");
  1738. llvm::Constant *OptionalPropertyArray =
  1739. llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
  1740. OptionalProperties.size()) , OptionalProperties);
  1741. llvm::Constant* OptionalPropertyListInitFields[] = {
  1742. llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
  1743. OptionalPropertyArray };
  1744. llvm::Constant *OptionalPropertyListInit =
  1745. llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
  1746. llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
  1747. OptionalPropertyListInit->getType(), false,
  1748. llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
  1749. ".objc_property_list");
  1750. // Protocols are objects containing lists of the methods implemented and
  1751. // protocols adopted.
  1752. llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
  1753. PtrToInt8Ty,
  1754. ProtocolList->getType(),
  1755. InstanceMethodList->getType(),
  1756. ClassMethodList->getType(),
  1757. OptionalInstanceMethodList->getType(),
  1758. OptionalClassMethodList->getType(),
  1759. PropertyList->getType(),
  1760. OptionalPropertyList->getType(),
  1761. nullptr);
  1762. std::vector<llvm::Constant*> Elements;
  1763. // The isa pointer must be set to a magic number so the runtime knows it's
  1764. // the correct layout.
  1765. Elements.push_back(llvm::ConstantExpr::getIntToPtr(
  1766. llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
  1767. Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
  1768. Elements.push_back(ProtocolList);
  1769. Elements.push_back(InstanceMethodList);
  1770. Elements.push_back(ClassMethodList);
  1771. Elements.push_back(OptionalInstanceMethodList);
  1772. Elements.push_back(OptionalClassMethodList);
  1773. Elements.push_back(PropertyList);
  1774. Elements.push_back(OptionalPropertyList);
  1775. ExistingProtocols[ProtocolName] =
  1776. llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
  1777. CGM.getPointerAlign(), ".objc_protocol"), IdTy);
  1778. }
  1779. void CGObjCGNU::GenerateProtocolHolderCategory() {
  1780. // Collect information about instance methods
  1781. SmallVector<Selector, 1> MethodSels;
  1782. SmallVector<llvm::Constant*, 1> MethodTypes;
  1783. std::vector<llvm::Constant*> Elements;
  1784. const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
  1785. const std::string CategoryName = "AnotherHack";
  1786. Elements.push_back(MakeConstantString(CategoryName));
  1787. Elements.push_back(MakeConstantString(ClassName));
  1788. // Instance method list
  1789. Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
  1790. ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
  1791. // Class method list
  1792. Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
  1793. ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
  1794. // Protocol list
  1795. llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
  1796. ExistingProtocols.size());
  1797. llvm::StructType *ProtocolListTy = llvm::StructType::get(
  1798. PtrTy, //Should be a recurisve pointer, but it's always NULL here.
  1799. SizeTy,
  1800. ProtocolArrayTy,
  1801. nullptr);
  1802. std::vector<llvm::Constant*> ProtocolElements;
  1803. for (llvm::StringMapIterator<llvm::Constant*> iter =
  1804. ExistingProtocols.begin(), endIter = ExistingProtocols.end();
  1805. iter != endIter ; iter++) {
  1806. llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
  1807. PtrTy);
  1808. ProtocolElements.push_back(Ptr);
  1809. }
  1810. llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
  1811. ProtocolElements);
  1812. ProtocolElements.clear();
  1813. ProtocolElements.push_back(NULLPtr);
  1814. ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
  1815. ExistingProtocols.size()));
  1816. ProtocolElements.push_back(ProtocolArray);
  1817. Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
  1818. ProtocolElements, CGM.getPointerAlign(),
  1819. ".objc_protocol_list"), PtrTy));
  1820. Categories.push_back(llvm::ConstantExpr::getBitCast(
  1821. MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
  1822. PtrTy, PtrTy, PtrTy, nullptr), Elements, CGM.getPointerAlign()),
  1823. PtrTy));
  1824. }
  1825. /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
  1826. /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
  1827. /// bits set to their values, LSB first, while larger ones are stored in a
  1828. /// structure of this / form:
  1829. ///
  1830. /// struct { int32_t length; int32_t values[length]; };
  1831. ///
  1832. /// The values in the array are stored in host-endian format, with the least
  1833. /// significant bit being assumed to come first in the bitfield. Therefore, a
  1834. /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
  1835. /// bitfield / with the 63rd bit set will be 1<<64.
  1836. llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
  1837. int bitCount = bits.size();
  1838. int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
  1839. if (bitCount < ptrBits) {
  1840. uint64_t val = 1;
  1841. for (int i=0 ; i<bitCount ; ++i) {
  1842. if (bits[i]) val |= 1ULL<<(i+1);
  1843. }
  1844. return llvm::ConstantInt::get(IntPtrTy, val);
  1845. }
  1846. SmallVector<llvm::Constant *, 8> values;
  1847. int v=0;
  1848. while (v < bitCount) {
  1849. int32_t word = 0;
  1850. for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
  1851. if (bits[v]) word |= 1<<i;
  1852. v++;
  1853. }
  1854. values.push_back(llvm::ConstantInt::get(Int32Ty, word));
  1855. }
  1856. llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
  1857. llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
  1858. llvm::Constant *fields[2] = {
  1859. llvm::ConstantInt::get(Int32Ty, values.size()),
  1860. array };
  1861. llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
  1862. nullptr), fields, CharUnits::fromQuantity(4));
  1863. llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
  1864. return ptr;
  1865. }
  1866. void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
  1867. std::string ClassName = OCD->getClassInterface()->getNameAsString();
  1868. std::string CategoryName = OCD->getNameAsString();
  1869. // Collect information about instance methods
  1870. SmallVector<Selector, 16> InstanceMethodSels;
  1871. SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
  1872. for (const auto *I : OCD->instance_methods()) {
  1873. InstanceMethodSels.push_back(I->getSelector());
  1874. std::string TypeStr;
  1875. CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
  1876. InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
  1877. }
  1878. // Collect information about class methods
  1879. SmallVector<Selector, 16> ClassMethodSels;
  1880. SmallVector<llvm::Constant*, 16> ClassMethodTypes;
  1881. for (const auto *I : OCD->class_methods()) {
  1882. ClassMethodSels.push_back(I->getSelector());
  1883. std::string TypeStr;
  1884. CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
  1885. ClassMethodTypes.push_back(MakeConstantString(TypeStr));
  1886. }
  1887. // Collect the names of referenced protocols
  1888. SmallVector<std::string, 16> Protocols;
  1889. const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
  1890. const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
  1891. for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
  1892. E = Protos.end(); I != E; ++I)
  1893. Protocols.push_back((*I)->getNameAsString());
  1894. std::vector<llvm::Constant*> Elements;
  1895. Elements.push_back(MakeConstantString(CategoryName));
  1896. Elements.push_back(MakeConstantString(ClassName));
  1897. // Instance method list
  1898. Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
  1899. ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
  1900. false), PtrTy));
  1901. // Class method list
  1902. Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
  1903. ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
  1904. PtrTy));
  1905. // Protocol list
  1906. Elements.push_back(llvm::ConstantExpr::getBitCast(
  1907. GenerateProtocolList(Protocols), PtrTy));
  1908. Categories.push_back(llvm::ConstantExpr::getBitCast(
  1909. MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
  1910. PtrTy, PtrTy, PtrTy, nullptr), Elements, CGM.getPointerAlign()),
  1911. PtrTy));
  1912. }
  1913. llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
  1914. SmallVectorImpl<Selector> &InstanceMethodSels,
  1915. SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
  1916. ASTContext &Context = CGM.getContext();
  1917. // Property metadata: name, attributes, attributes2, padding1, padding2,
  1918. // setter name, setter types, getter name, getter types.
  1919. llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
  1920. PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
  1921. PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
  1922. std::vector<llvm::Constant*> Properties;
  1923. // Add all of the property methods need adding to the method list and to the
  1924. // property metadata list.
  1925. for (auto *propertyImpl : OID->property_impls()) {
  1926. std::vector<llvm::Constant*> Fields;
  1927. ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
  1928. bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
  1929. ObjCPropertyImplDecl::Synthesize);
  1930. bool isDynamic = (propertyImpl->getPropertyImplementation() ==
  1931. ObjCPropertyImplDecl::Dynamic);
  1932. Fields.push_back(MakePropertyEncodingString(property, OID));
  1933. PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
  1934. if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
  1935. std::string TypeStr;
  1936. Context.getObjCEncodingForMethodDecl(getter,TypeStr);
  1937. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  1938. if (isSynthesized) {
  1939. InstanceMethodTypes.push_back(TypeEncoding);
  1940. InstanceMethodSels.push_back(getter->getSelector());
  1941. }
  1942. Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
  1943. Fields.push_back(TypeEncoding);
  1944. } else {
  1945. Fields.push_back(NULLPtr);
  1946. Fields.push_back(NULLPtr);
  1947. }
  1948. if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
  1949. std::string TypeStr;
  1950. Context.getObjCEncodingForMethodDecl(setter,TypeStr);
  1951. llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
  1952. if (isSynthesized) {
  1953. InstanceMethodTypes.push_back(TypeEncoding);
  1954. InstanceMethodSels.push_back(setter->getSelector());
  1955. }
  1956. Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
  1957. Fields.push_back(TypeEncoding);
  1958. } else {
  1959. Fields.push_back(NULLPtr);
  1960. Fields.push_back(NULLPtr);
  1961. }
  1962. Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
  1963. }
  1964. llvm::ArrayType *PropertyArrayTy =
  1965. llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
  1966. llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
  1967. Properties);
  1968. llvm::Constant* PropertyListInitFields[] =
  1969. {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
  1970. llvm::Constant *PropertyListInit =
  1971. llvm::ConstantStruct::getAnon(PropertyListInitFields);
  1972. return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
  1973. llvm::GlobalValue::InternalLinkage, PropertyListInit,
  1974. ".objc_property_list");
  1975. }
  1976. void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
  1977. // Get the class declaration for which the alias is specified.
  1978. ObjCInterfaceDecl *ClassDecl =
  1979. const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
  1980. ClassAliases.emplace_back(ClassDecl->getNameAsString(),
  1981. OAD->getNameAsString());
  1982. }
  1983. void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
  1984. ASTContext &Context = CGM.getContext();
  1985. // Get the superclass name.
  1986. const ObjCInterfaceDecl * SuperClassDecl =
  1987. OID->getClassInterface()->getSuperClass();
  1988. std::string SuperClassName;
  1989. if (SuperClassDecl) {
  1990. SuperClassName = SuperClassDecl->getNameAsString();
  1991. EmitClassRef(SuperClassName);
  1992. }
  1993. // Get the class name
  1994. ObjCInterfaceDecl *ClassDecl =
  1995. const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
  1996. std::string ClassName = ClassDecl->getNameAsString();
  1997. // Emit the symbol that is used to generate linker errors if this class is
  1998. // referenced in other modules but not declared.
  1999. std::string classSymbolName = "__objc_class_name_" + ClassName;
  2000. if (llvm::GlobalVariable *symbol =
  2001. TheModule.getGlobalVariable(classSymbolName)) {
  2002. symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
  2003. } else {
  2004. new llvm::GlobalVariable(TheModule, LongTy, false,
  2005. llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
  2006. classSymbolName);
  2007. }
  2008. // Get the size of instances.
  2009. int instanceSize =
  2010. Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
  2011. // Collect information about instance variables.
  2012. SmallVector<llvm::Constant*, 16> IvarNames;
  2013. SmallVector<llvm::Constant*, 16> IvarTypes;
  2014. SmallVector<llvm::Constant*, 16> IvarOffsets;
  2015. std::vector<llvm::Constant*> IvarOffsetValues;
  2016. SmallVector<bool, 16> WeakIvars;
  2017. SmallVector<bool, 16> StrongIvars;
  2018. int superInstanceSize = !SuperClassDecl ? 0 :
  2019. Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
  2020. // For non-fragile ivars, set the instance size to 0 - {the size of just this
  2021. // class}. The runtime will then set this to the correct value on load.
  2022. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  2023. instanceSize = 0 - (instanceSize - superInstanceSize);
  2024. }
  2025. for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
  2026. IVD = IVD->getNextIvar()) {
  2027. // Store the name
  2028. IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
  2029. // Get the type encoding for this ivar
  2030. std::string TypeStr;
  2031. Context.getObjCEncodingForType(IVD->getType(), TypeStr);
  2032. IvarTypes.push_back(MakeConstantString(TypeStr));
  2033. // Get the offset
  2034. uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
  2035. uint64_t Offset = BaseOffset;
  2036. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  2037. Offset = BaseOffset - superInstanceSize;
  2038. }
  2039. llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
  2040. // Create the direct offset value
  2041. std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
  2042. IVD->getNameAsString();
  2043. llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
  2044. if (OffsetVar) {
  2045. OffsetVar->setInitializer(OffsetValue);
  2046. // If this is the real definition, change its linkage type so that
  2047. // different modules will use this one, rather than their private
  2048. // copy.
  2049. OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2050. } else
  2051. OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
  2052. false, llvm::GlobalValue::ExternalLinkage,
  2053. OffsetValue,
  2054. "__objc_ivar_offset_value_" + ClassName +"." +
  2055. IVD->getNameAsString());
  2056. IvarOffsets.push_back(OffsetValue);
  2057. IvarOffsetValues.push_back(OffsetVar);
  2058. Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
  2059. switch (lt) {
  2060. case Qualifiers::OCL_Strong:
  2061. StrongIvars.push_back(true);
  2062. WeakIvars.push_back(false);
  2063. break;
  2064. case Qualifiers::OCL_Weak:
  2065. StrongIvars.push_back(false);
  2066. WeakIvars.push_back(true);
  2067. break;
  2068. default:
  2069. StrongIvars.push_back(false);
  2070. WeakIvars.push_back(false);
  2071. }
  2072. }
  2073. llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
  2074. llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
  2075. llvm::GlobalVariable *IvarOffsetArray =
  2076. MakeGlobalArray(PtrToIntTy, IvarOffsetValues, CGM.getPointerAlign(),
  2077. ".ivar.offsets");
  2078. // Collect information about instance methods
  2079. SmallVector<Selector, 16> InstanceMethodSels;
  2080. SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
  2081. for (const auto *I : OID->instance_methods()) {
  2082. InstanceMethodSels.push_back(I->getSelector());
  2083. std::string TypeStr;
  2084. Context.getObjCEncodingForMethodDecl(I,TypeStr);
  2085. InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
  2086. }
  2087. llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
  2088. InstanceMethodTypes);
  2089. // Collect information about class methods
  2090. SmallVector<Selector, 16> ClassMethodSels;
  2091. SmallVector<llvm::Constant*, 16> ClassMethodTypes;
  2092. for (const auto *I : OID->class_methods()) {
  2093. ClassMethodSels.push_back(I->getSelector());
  2094. std::string TypeStr;
  2095. Context.getObjCEncodingForMethodDecl(I,TypeStr);
  2096. ClassMethodTypes.push_back(MakeConstantString(TypeStr));
  2097. }
  2098. // Collect the names of referenced protocols
  2099. SmallVector<std::string, 16> Protocols;
  2100. for (const auto *I : ClassDecl->protocols())
  2101. Protocols.push_back(I->getNameAsString());
  2102. // Get the superclass pointer.
  2103. llvm::Constant *SuperClass;
  2104. if (!SuperClassName.empty()) {
  2105. SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
  2106. } else {
  2107. SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
  2108. }
  2109. // Empty vector used to construct empty method lists
  2110. SmallVector<llvm::Constant*, 1> empty;
  2111. // Generate the method and instance variable lists
  2112. llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
  2113. InstanceMethodSels, InstanceMethodTypes, false);
  2114. llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
  2115. ClassMethodSels, ClassMethodTypes, true);
  2116. llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
  2117. IvarOffsets);
  2118. // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
  2119. // we emit a symbol containing the offset for each ivar in the class. This
  2120. // allows code compiled for the non-Fragile ABI to inherit from code compiled
  2121. // for the legacy ABI, without causing problems. The converse is also
  2122. // possible, but causes all ivar accesses to be fragile.
  2123. // Offset pointer for getting at the correct field in the ivar list when
  2124. // setting up the alias. These are: The base address for the global, the
  2125. // ivar array (second field), the ivar in this list (set for each ivar), and
  2126. // the offset (third field in ivar structure)
  2127. llvm::Type *IndexTy = Int32Ty;
  2128. llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
  2129. llvm::ConstantInt::get(IndexTy, 1), nullptr,
  2130. llvm::ConstantInt::get(IndexTy, 2) };
  2131. unsigned ivarIndex = 0;
  2132. for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
  2133. IVD = IVD->getNextIvar()) {
  2134. const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
  2135. + IVD->getNameAsString();
  2136. offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
  2137. // Get the correct ivar field
  2138. llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
  2139. cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
  2140. offsetPointerIndexes);
  2141. // Get the existing variable, if one exists.
  2142. llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
  2143. if (offset) {
  2144. offset->setInitializer(offsetValue);
  2145. // If this is the real definition, change its linkage type so that
  2146. // different modules will use this one, rather than their private
  2147. // copy.
  2148. offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2149. } else {
  2150. // Add a new alias if there isn't one already.
  2151. offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
  2152. false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
  2153. (void) offset; // Silence dead store warning.
  2154. }
  2155. ++ivarIndex;
  2156. }
  2157. llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
  2158. //Generate metaclass for class methods
  2159. llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
  2160. NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], GenerateIvarList(
  2161. empty, empty, empty), ClassMethodList, NULLPtr,
  2162. NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
  2163. // Generate the class structure
  2164. llvm::Constant *ClassStruct =
  2165. GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
  2166. ClassName.c_str(), nullptr,
  2167. llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
  2168. MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
  2169. Properties, StrongIvarBitmap, WeakIvarBitmap);
  2170. // Resolve the class aliases, if they exist.
  2171. if (ClassPtrAlias) {
  2172. ClassPtrAlias->replaceAllUsesWith(
  2173. llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
  2174. ClassPtrAlias->eraseFromParent();
  2175. ClassPtrAlias = nullptr;
  2176. }
  2177. if (MetaClassPtrAlias) {
  2178. MetaClassPtrAlias->replaceAllUsesWith(
  2179. llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
  2180. MetaClassPtrAlias->eraseFromParent();
  2181. MetaClassPtrAlias = nullptr;
  2182. }
  2183. // Add class structure to list to be added to the symtab later
  2184. ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
  2185. Classes.push_back(ClassStruct);
  2186. }
  2187. llvm::Function *CGObjCGNU::ModuleInitFunction() {
  2188. // Only emit an ObjC load function if no Objective-C stuff has been called
  2189. if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
  2190. ExistingProtocols.empty() && SelectorTable.empty())
  2191. return nullptr;
  2192. // Add all referenced protocols to a category.
  2193. GenerateProtocolHolderCategory();
  2194. llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
  2195. SelectorTy->getElementType());
  2196. llvm::Type *SelStructPtrTy = SelectorTy;
  2197. if (!SelStructTy) {
  2198. SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
  2199. SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
  2200. }
  2201. std::vector<llvm::Constant*> Elements;
  2202. llvm::Constant *Statics = NULLPtr;
  2203. // Generate statics list:
  2204. if (!ConstantStrings.empty()) {
  2205. llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
  2206. ConstantStrings.size() + 1);
  2207. ConstantStrings.push_back(NULLPtr);
  2208. StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
  2209. if (StringClass.empty()) StringClass = "NXConstantString";
  2210. Elements.push_back(MakeConstantString(StringClass,
  2211. ".objc_static_class_name"));
  2212. Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
  2213. ConstantStrings));
  2214. llvm::StructType *StaticsListTy =
  2215. llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr);
  2216. llvm::Type *StaticsListPtrTy =
  2217. llvm::PointerType::getUnqual(StaticsListTy);
  2218. Statics = MakeGlobal(StaticsListTy, Elements, CGM.getPointerAlign(),
  2219. ".objc_statics");
  2220. llvm::ArrayType *StaticsListArrayTy =
  2221. llvm::ArrayType::get(StaticsListPtrTy, 2);
  2222. Elements.clear();
  2223. Elements.push_back(Statics);
  2224. Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
  2225. Statics = MakeGlobal(StaticsListArrayTy, Elements,
  2226. CGM.getPointerAlign(), ".objc_statics_ptr");
  2227. Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
  2228. }
  2229. // Array of classes, categories, and constant objects
  2230. llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
  2231. Classes.size() + Categories.size() + 2);
  2232. llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
  2233. llvm::Type::getInt16Ty(VMContext),
  2234. llvm::Type::getInt16Ty(VMContext),
  2235. ClassListTy, nullptr);
  2236. Elements.clear();
  2237. // Pointer to an array of selectors used in this module.
  2238. std::vector<llvm::Constant*> Selectors;
  2239. std::vector<llvm::GlobalAlias*> SelectorAliases;
  2240. for (SelectorMap::iterator iter = SelectorTable.begin(),
  2241. iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
  2242. std::string SelNameStr = iter->first.getAsString();
  2243. llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
  2244. SmallVectorImpl<TypedSelector> &Types = iter->second;
  2245. for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
  2246. e = Types.end() ; i!=e ; i++) {
  2247. llvm::Constant *SelectorTypeEncoding = NULLPtr;
  2248. if (!i->first.empty())
  2249. SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
  2250. Elements.push_back(SelName);
  2251. Elements.push_back(SelectorTypeEncoding);
  2252. Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
  2253. Elements.clear();
  2254. // Store the selector alias for later replacement
  2255. SelectorAliases.push_back(i->second);
  2256. }
  2257. }
  2258. unsigned SelectorCount = Selectors.size();
  2259. // NULL-terminate the selector list. This should not actually be required,
  2260. // because the selector list has a length field. Unfortunately, the GCC
  2261. // runtime decides to ignore the length field and expects a NULL terminator,
  2262. // and GCC cooperates with this by always setting the length to 0.
  2263. Elements.push_back(NULLPtr);
  2264. Elements.push_back(NULLPtr);
  2265. Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
  2266. Elements.clear();
  2267. // Number of static selectors
  2268. Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
  2269. llvm::GlobalVariable *SelectorList =
  2270. MakeGlobalArray(SelStructTy, Selectors, CGM.getPointerAlign(),
  2271. ".objc_selector_list");
  2272. Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
  2273. SelStructPtrTy));
  2274. // Now that all of the static selectors exist, create pointers to them.
  2275. for (unsigned int i=0 ; i<SelectorCount ; i++) {
  2276. llvm::Constant *Idxs[] = {Zeros[0],
  2277. llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
  2278. // FIXME: We're generating redundant loads and stores here!
  2279. llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(
  2280. SelectorList->getValueType(), SelectorList, makeArrayRef(Idxs, 2));
  2281. // If selectors are defined as an opaque type, cast the pointer to this
  2282. // type.
  2283. SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
  2284. SelectorAliases[i]->replaceAllUsesWith(SelPtr);
  2285. SelectorAliases[i]->eraseFromParent();
  2286. }
  2287. // Number of classes defined.
  2288. Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
  2289. Classes.size()));
  2290. // Number of categories defined
  2291. Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
  2292. Categories.size()));
  2293. // Create an array of classes, then categories, then static object instances
  2294. Classes.insert(Classes.end(), Categories.begin(), Categories.end());
  2295. // NULL-terminated list of static object instances (mainly constant strings)
  2296. Classes.push_back(Statics);
  2297. Classes.push_back(NULLPtr);
  2298. llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
  2299. Elements.push_back(ClassList);
  2300. // Construct the symbol table
  2301. llvm::Constant *SymTab =
  2302. MakeGlobal(SymTabTy, Elements, CGM.getPointerAlign());
  2303. // The symbol table is contained in a module which has some version-checking
  2304. // constants
  2305. llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
  2306. PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
  2307. (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
  2308. Elements.clear();
  2309. // Runtime version, used for ABI compatibility checking.
  2310. Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
  2311. // sizeof(ModuleTy)
  2312. llvm::DataLayout td(&TheModule);
  2313. Elements.push_back(
  2314. llvm::ConstantInt::get(LongTy,
  2315. td.getTypeSizeInBits(ModuleTy) /
  2316. CGM.getContext().getCharWidth()));
  2317. // The path to the source file where this module was declared
  2318. SourceManager &SM = CGM.getContext().getSourceManager();
  2319. const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
  2320. std::string path =
  2321. std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
  2322. Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
  2323. Elements.push_back(SymTab);
  2324. if (RuntimeVersion >= 10)
  2325. switch (CGM.getLangOpts().getGC()) {
  2326. case LangOptions::GCOnly:
  2327. Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
  2328. break;
  2329. case LangOptions::NonGC:
  2330. if (CGM.getLangOpts().ObjCAutoRefCount)
  2331. Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
  2332. else
  2333. Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
  2334. break;
  2335. case LangOptions::HybridGC:
  2336. Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
  2337. break;
  2338. }
  2339. llvm::Value *Module = MakeGlobal(ModuleTy, Elements, CGM.getPointerAlign());
  2340. // Create the load function calling the runtime entry point with the module
  2341. // structure
  2342. llvm::Function * LoadFunction = llvm::Function::Create(
  2343. llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
  2344. llvm::GlobalValue::InternalLinkage, ".objc_load_function",
  2345. &TheModule);
  2346. llvm::BasicBlock *EntryBB =
  2347. llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
  2348. CGBuilderTy Builder(CGM, VMContext);
  2349. Builder.SetInsertPoint(EntryBB);
  2350. llvm::FunctionType *FT =
  2351. llvm::FunctionType::get(Builder.getVoidTy(),
  2352. llvm::PointerType::getUnqual(ModuleTy), true);
  2353. llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
  2354. Builder.CreateCall(Register, Module);
  2355. if (!ClassAliases.empty()) {
  2356. llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
  2357. llvm::FunctionType *RegisterAliasTy =
  2358. llvm::FunctionType::get(Builder.getVoidTy(),
  2359. ArgTypes, false);
  2360. llvm::Function *RegisterAlias = llvm::Function::Create(
  2361. RegisterAliasTy,
  2362. llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
  2363. &TheModule);
  2364. llvm::BasicBlock *AliasBB =
  2365. llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
  2366. llvm::BasicBlock *NoAliasBB =
  2367. llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
  2368. // Branch based on whether the runtime provided class_registerAlias_np()
  2369. llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
  2370. llvm::Constant::getNullValue(RegisterAlias->getType()));
  2371. Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
  2372. // The true branch (has alias registration function):
  2373. Builder.SetInsertPoint(AliasBB);
  2374. // Emit alias registration calls:
  2375. for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
  2376. iter != ClassAliases.end(); ++iter) {
  2377. llvm::Constant *TheClass =
  2378. TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
  2379. true);
  2380. if (TheClass) {
  2381. TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
  2382. Builder.CreateCall(RegisterAlias,
  2383. {TheClass, MakeConstantString(iter->second)});
  2384. }
  2385. }
  2386. // Jump to end:
  2387. Builder.CreateBr(NoAliasBB);
  2388. // Missing alias registration function, just return from the function:
  2389. Builder.SetInsertPoint(NoAliasBB);
  2390. }
  2391. Builder.CreateRetVoid();
  2392. return LoadFunction;
  2393. }
  2394. llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
  2395. const ObjCContainerDecl *CD) {
  2396. const ObjCCategoryImplDecl *OCD =
  2397. dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
  2398. StringRef CategoryName = OCD ? OCD->getName() : "";
  2399. StringRef ClassName = CD->getName();
  2400. Selector MethodName = OMD->getSelector();
  2401. bool isClassMethod = !OMD->isInstanceMethod();
  2402. CodeGenTypes &Types = CGM.getTypes();
  2403. llvm::FunctionType *MethodTy =
  2404. Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
  2405. std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
  2406. MethodName, isClassMethod);
  2407. llvm::Function *Method
  2408. = llvm::Function::Create(MethodTy,
  2409. llvm::GlobalValue::InternalLinkage,
  2410. FunctionName,
  2411. &TheModule);
  2412. return Method;
  2413. }
  2414. llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
  2415. return GetPropertyFn;
  2416. }
  2417. llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
  2418. return SetPropertyFn;
  2419. }
  2420. llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
  2421. bool copy) {
  2422. return nullptr;
  2423. }
  2424. llvm::Constant *CGObjCGNU::GetGetStructFunction() {
  2425. return GetStructPropertyFn;
  2426. }
  2427. llvm::Constant *CGObjCGNU::GetSetStructFunction() {
  2428. return SetStructPropertyFn;
  2429. }
  2430. llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
  2431. return nullptr;
  2432. }
  2433. llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
  2434. return nullptr;
  2435. }
  2436. llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
  2437. return EnumerationMutationFn;
  2438. }
  2439. void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
  2440. const ObjCAtSynchronizedStmt &S) {
  2441. EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
  2442. }
  2443. void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
  2444. const ObjCAtTryStmt &S) {
  2445. // Unlike the Apple non-fragile runtimes, which also uses
  2446. // unwind-based zero cost exceptions, the GNU Objective C runtime's
  2447. // EH support isn't a veneer over C++ EH. Instead, exception
  2448. // objects are created by objc_exception_throw and destroyed by
  2449. // the personality function; this avoids the need for bracketing
  2450. // catch handlers with calls to __blah_begin_catch/__blah_end_catch
  2451. // (or even _Unwind_DeleteException), but probably doesn't
  2452. // interoperate very well with foreign exceptions.
  2453. //
  2454. // In Objective-C++ mode, we actually emit something equivalent to the C++
  2455. // exception handler.
  2456. EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
  2457. }
  2458. void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
  2459. const ObjCAtThrowStmt &S,
  2460. bool ClearInsertionPoint) {
  2461. llvm::Value *ExceptionAsObject;
  2462. if (const Expr *ThrowExpr = S.getThrowExpr()) {
  2463. llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
  2464. ExceptionAsObject = Exception;
  2465. } else {
  2466. assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
  2467. "Unexpected rethrow outside @catch block.");
  2468. ExceptionAsObject = CGF.ObjCEHValueStack.back();
  2469. }
  2470. ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
  2471. llvm::CallSite Throw =
  2472. CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
  2473. Throw.setDoesNotReturn();
  2474. CGF.Builder.CreateUnreachable();
  2475. if (ClearInsertionPoint)
  2476. CGF.Builder.ClearInsertionPoint();
  2477. }
  2478. llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
  2479. Address AddrWeakObj) {
  2480. CGBuilderTy &B = CGF.Builder;
  2481. AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
  2482. return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
  2483. AddrWeakObj.getPointer());
  2484. }
  2485. void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
  2486. llvm::Value *src, Address dst) {
  2487. CGBuilderTy &B = CGF.Builder;
  2488. src = EnforceType(B, src, IdTy);
  2489. dst = EnforceType(B, dst, PtrToIdTy);
  2490. B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
  2491. {src, dst.getPointer()});
  2492. }
  2493. void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
  2494. llvm::Value *src, Address dst,
  2495. bool threadlocal) {
  2496. CGBuilderTy &B = CGF.Builder;
  2497. src = EnforceType(B, src, IdTy);
  2498. dst = EnforceType(B, dst, PtrToIdTy);
  2499. // FIXME. Add threadloca assign API
  2500. assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
  2501. B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
  2502. {src, dst.getPointer()});
  2503. }
  2504. void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
  2505. llvm::Value *src, Address dst,
  2506. llvm::Value *ivarOffset) {
  2507. CGBuilderTy &B = CGF.Builder;
  2508. src = EnforceType(B, src, IdTy);
  2509. dst = EnforceType(B, dst, IdTy);
  2510. B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
  2511. {src, dst.getPointer(), ivarOffset});
  2512. }
  2513. void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
  2514. llvm::Value *src, Address dst) {
  2515. CGBuilderTy &B = CGF.Builder;
  2516. src = EnforceType(B, src, IdTy);
  2517. dst = EnforceType(B, dst, PtrToIdTy);
  2518. B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
  2519. {src, dst.getPointer()});
  2520. }
  2521. void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
  2522. Address DestPtr,
  2523. Address SrcPtr,
  2524. llvm::Value *Size) {
  2525. CGBuilderTy &B = CGF.Builder;
  2526. DestPtr = EnforceType(B, DestPtr, PtrTy);
  2527. SrcPtr = EnforceType(B, SrcPtr, PtrTy);
  2528. B.CreateCall(MemMoveFn.getType(), MemMoveFn,
  2529. {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
  2530. }
  2531. llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
  2532. const ObjCInterfaceDecl *ID,
  2533. const ObjCIvarDecl *Ivar) {
  2534. const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
  2535. + '.' + Ivar->getNameAsString();
  2536. // Emit the variable and initialize it with what we think the correct value
  2537. // is. This allows code compiled with non-fragile ivars to work correctly
  2538. // when linked against code which isn't (most of the time).
  2539. llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
  2540. if (!IvarOffsetPointer) {
  2541. // This will cause a run-time crash if we accidentally use it. A value of
  2542. // 0 would seem more sensible, but will silently overwrite the isa pointer
  2543. // causing a great deal of confusion.
  2544. uint64_t Offset = -1;
  2545. // We can't call ComputeIvarBaseOffset() here if we have the
  2546. // implementation, because it will create an invalid ASTRecordLayout object
  2547. // that we are then stuck with forever, so we only initialize the ivar
  2548. // offset variable with a guess if we only have the interface. The
  2549. // initializer will be reset later anyway, when we are generating the class
  2550. // description.
  2551. if (!CGM.getContext().getObjCImplementation(
  2552. const_cast<ObjCInterfaceDecl *>(ID)))
  2553. Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
  2554. llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
  2555. /*isSigned*/true);
  2556. // Don't emit the guess in non-PIC code because the linker will not be able
  2557. // to replace it with the real version for a library. In non-PIC code you
  2558. // must compile with the fragile ABI if you want to use ivars from a
  2559. // GCC-compiled class.
  2560. if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
  2561. llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
  2562. Int32Ty, false,
  2563. llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
  2564. IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
  2565. IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
  2566. IvarOffsetGV, Name);
  2567. } else {
  2568. IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
  2569. llvm::Type::getInt32PtrTy(VMContext), false,
  2570. llvm::GlobalValue::ExternalLinkage, nullptr, Name);
  2571. }
  2572. }
  2573. return IvarOffsetPointer;
  2574. }
  2575. LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
  2576. QualType ObjectTy,
  2577. llvm::Value *BaseValue,
  2578. const ObjCIvarDecl *Ivar,
  2579. unsigned CVRQualifiers) {
  2580. const ObjCInterfaceDecl *ID =
  2581. ObjectTy->getAs<ObjCObjectType>()->getInterface();
  2582. return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
  2583. EmitIvarOffset(CGF, ID, Ivar));
  2584. }
  2585. static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
  2586. const ObjCInterfaceDecl *OID,
  2587. const ObjCIvarDecl *OIVD) {
  2588. for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
  2589. next = next->getNextIvar()) {
  2590. if (OIVD == next)
  2591. return OID;
  2592. }
  2593. // Otherwise check in the super class.
  2594. if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
  2595. return FindIvarInterface(Context, Super, OIVD);
  2596. return nullptr;
  2597. }
  2598. llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
  2599. const ObjCInterfaceDecl *Interface,
  2600. const ObjCIvarDecl *Ivar) {
  2601. if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
  2602. Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
  2603. if (RuntimeVersion < 10)
  2604. return CGF.Builder.CreateZExtOrBitCast(
  2605. CGF.Builder.CreateDefaultAlignedLoad(CGF.Builder.CreateAlignedLoad(
  2606. ObjCIvarOffsetVariable(Interface, Ivar),
  2607. CGF.getPointerAlign(), "ivar")),
  2608. PtrDiffTy);
  2609. std::string name = "__objc_ivar_offset_value_" +
  2610. Interface->getNameAsString() +"." + Ivar->getNameAsString();
  2611. CharUnits Align = CGM.getIntAlign();
  2612. llvm::Value *Offset = TheModule.getGlobalVariable(name);
  2613. if (!Offset) {
  2614. auto GV = new llvm::GlobalVariable(TheModule, IntTy,
  2615. false, llvm::GlobalValue::LinkOnceAnyLinkage,
  2616. llvm::Constant::getNullValue(IntTy), name);
  2617. GV->setAlignment(Align.getQuantity());
  2618. Offset = GV;
  2619. }
  2620. Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
  2621. if (Offset->getType() != PtrDiffTy)
  2622. Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
  2623. return Offset;
  2624. }
  2625. uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
  2626. return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
  2627. }
  2628. CGObjCRuntime *
  2629. clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
  2630. switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
  2631. case ObjCRuntime::GNUstep:
  2632. return new CGObjCGNUstep(CGM);
  2633. case ObjCRuntime::GCC:
  2634. return new CGObjCGCC(CGM);
  2635. case ObjCRuntime::ObjFW:
  2636. return new CGObjCObjFW(CGM);
  2637. case ObjCRuntime::FragileMacOSX:
  2638. case ObjCRuntime::MacOSX:
  2639. case ObjCRuntime::iOS:
  2640. case ObjCRuntime::WatchOS:
  2641. llvm_unreachable("these runtimes are not GNU runtimes");
  2642. }
  2643. llvm_unreachable("bad runtime");
  2644. }