CGObjCGNU.cpp 122 KB

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