blob: 39395437b6676ee74d387730a5f92fdf2ab25ffa [file] [log] [blame]
Fariborz Jahanian11671902012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
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// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekcdf81492012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000031#include <memory>
Fariborz Jahanian11671902012-02-07 17:11:38 +000032
33using namespace clang;
34using llvm::utostr;
35
36namespace {
37 class RewriteModernObjC : public ASTConsumer {
38 protected:
39
40 enum {
41 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
42 block, ... */
43 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
44 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
45 __block variable */
46 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
47 helpers */
48 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
49 support routines */
50 BLOCK_BYREF_CURRENT_MAX = 256
51 };
52
53 enum {
54 BLOCK_NEEDS_FREE = (1 << 24),
55 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
56 BLOCK_HAS_CXX_OBJ = (1 << 26),
57 BLOCK_IS_GC = (1 << 27),
58 BLOCK_IS_GLOBAL = (1 << 28),
59 BLOCK_HAS_DESCRIPTOR = (1 << 29)
60 };
Fariborz Jahanian11671902012-02-07 17:11:38 +000061
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000121
Fariborz Jahanian11671902012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000133
John McCall113bee02012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000135
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000136
Fariborz Jahanian11671902012-02-07 17:11:38 +0000137 // Block related declarations.
138 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
140 SmallVector<ValueDecl *, 8> BlockByRefDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
142 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
143 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
144 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
145
146 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000150 // ivar bitfield grouping containers
151 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
152 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
153 // This container maps an <class, group number for ivar> tuple to the type
154 // of the struct where the bitfield belongs.
155 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000157
Fariborz Jahanian11671902012-02-07 17:11:38 +0000158 // This maps an original source AST to it's rewritten form. This allows
159 // us to avoid rewriting the same node twice (which is very uncommon).
160 // This is needed to support some of the exotic property rewriting.
161 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
162
163 // Needed for header files being rewritten
164 bool IsHeader;
165 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000166 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000167 bool objc_impl_method;
168
169 bool DisableReplaceStmt;
170 class DisableReplaceStmtScope {
171 RewriteModernObjC &R;
172 bool SavedValue;
173
174 public:
175 DisableReplaceStmtScope(RewriteModernObjC &R)
176 : R(R), SavedValue(R.DisableReplaceStmt) {
177 R.DisableReplaceStmt = true;
178 }
179 ~DisableReplaceStmtScope() {
180 R.DisableReplaceStmt = SavedValue;
181 }
182 };
183 void InitializeCommon(ASTContext &context);
184
185 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000186 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000187 // Top Level Driver code.
188 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
189 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
190 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
191 if (!Class->isThisDeclarationADefinition()) {
192 RewriteForwardClassDecl(D);
193 break;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000194 } else {
195 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000196 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000197 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000198 }
199 }
200
201 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
202 if (!Proto->isThisDeclarationADefinition()) {
203 RewriteForwardProtocolDecl(D);
204 break;
205 }
206 }
207
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000208 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
209 // Under modern abi, we cannot translate body of the function
210 // yet until all class extensions and its implementation is seen.
211 // This is because they may introduce new bitfields which must go
212 // into their grouping struct.
213 if (FDecl->isThisDeclarationADefinition() &&
214 // Not c functions defined inside an objc container.
215 !FDecl->isTopLevelDeclInObjCContainer()) {
216 FunctionDefinitionsSeen.push_back(FDecl);
217 break;
218 }
219 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000220 HandleTopLevelSingleDecl(*I);
221 }
222 return true;
223 }
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000224
225 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
226 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
227 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
228 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
229 RewriteBlockPointerDecl(TD);
230 else if (TD->getUnderlyingType()->isFunctionPointerType())
231 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
232 else
233 RewriteObjCQualifiedInterfaceTypes(TD);
234 }
235 }
236 return;
237 }
238
Fariborz Jahanian11671902012-02-07 17:11:38 +0000239 void HandleTopLevelSingleDecl(Decl *D);
240 void HandleDeclInMainFile(Decl *D);
241 RewriteModernObjC(std::string inFile, raw_ostream *OS,
242 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000243 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000244
245 ~RewriteModernObjC() {}
246
247 virtual void HandleTranslationUnit(ASTContext &C);
248
249 void ReplaceStmt(Stmt *Old, Stmt *New) {
250 Stmt *ReplacingStmt = ReplacedNodes[Old];
251
252 if (ReplacingStmt)
253 return; // We can't rewrite the same node twice.
254
255 if (DisableReplaceStmt)
256 return;
257
258 // If replacement succeeded or warning disabled return with no warning.
259 if (!Rewrite.ReplaceStmt(Old, New)) {
260 ReplacedNodes[Old] = New;
261 return;
262 }
263 if (SilenceRewriteMacroWarning)
264 return;
265 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
266 << Old->getSourceRange();
267 }
268
269 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
270 if (DisableReplaceStmt)
271 return;
272
273 // Measure the old text.
274 int Size = Rewrite.getRangeSize(SrcRange);
275 if (Size == -1) {
276 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
277 << Old->getSourceRange();
278 return;
279 }
280 // Get the new text.
281 std::string SStr;
282 llvm::raw_string_ostream S(SStr);
Richard Smith235341b2012-08-16 03:56:14 +0000283 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000284 const std::string &Str = S.str();
285
286 // If replacement succeeded or warning disabled return with no warning.
287 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
288 ReplacedNodes[Old] = New;
289 return;
290 }
291 if (SilenceRewriteMacroWarning)
292 return;
293 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
294 << Old->getSourceRange();
295 }
296
297 void InsertText(SourceLocation Loc, StringRef Str,
298 bool InsertAfter = true) {
299 // If insertion succeeded or warning disabled return with no warning.
300 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
301 SilenceRewriteMacroWarning)
302 return;
303
304 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
305 }
306
307 void ReplaceText(SourceLocation Start, unsigned OrigLength,
308 StringRef Str) {
309 // If removal succeeded or warning disabled return with no warning.
310 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
311 SilenceRewriteMacroWarning)
312 return;
313
314 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
315 }
316
317 // Syntactic Rewriting.
318 void RewriteRecordBody(RecordDecl *RD);
319 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000320 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000321 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
322 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000323 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000324 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000325 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
326 const std::string &typedefString);
327 void RewriteImplementations();
328 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
329 ObjCImplementationDecl *IMD,
330 ObjCCategoryImplDecl *CID);
331 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
332 void RewriteImplementationDecl(Decl *Dcl);
333 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
334 ObjCMethodDecl *MDecl, std::string &ResultStr);
335 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
336 const FunctionType *&FPRetType);
337 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
338 ValueDecl *VD, bool def=false);
339 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
340 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
341 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000342 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000343 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
344 void RewriteProperty(ObjCPropertyDecl *prop);
345 void RewriteFunctionDecl(FunctionDecl *FD);
346 void RewriteBlockPointerType(std::string& Str, QualType Type);
347 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000348 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000349 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
350 void RewriteTypeOfDecl(VarDecl *VD);
351 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000352
353 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000354
355 // Expression Rewriting.
356 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
357 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
358 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
359 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
360 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
361 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
362 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000363 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000364 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000365 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000366 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000367 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000368 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000369 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000370 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
371 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
372 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
373 SourceLocation OrigEnd);
374 Stmt *RewriteBreakStmt(BreakStmt *S);
375 Stmt *RewriteContinueStmt(ContinueStmt *S);
376 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000377 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000378 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000379
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000380 // Computes ivar bitfield group no.
381 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
382 // Names field decl. for ivar bitfield group.
383 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
384 // Names struct type for ivar bitfield group.
385 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
386 // Names symbol for ivar bitfield group field offset.
387 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
388 // Given an ivar bitfield, it builds (or finds) its group record type.
389 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
390 QualType SynthesizeBitfieldGroupStructType(
391 ObjCIvarDecl *IV,
392 SmallVectorImpl<ObjCIvarDecl *> &IVars);
393
Fariborz Jahanian11671902012-02-07 17:11:38 +0000394 // Block rewriting.
395 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
396
397 // Block specific rewrite rules.
398 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000399 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000400 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000401 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
402 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
403
404 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
405 std::string &Result);
406
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000407 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000408 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000409 bool &IsNamedDefinition);
410 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
411 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000412
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000413 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
414
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000415 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
416 std::string &Result);
417
Fariborz Jahanian11671902012-02-07 17:11:38 +0000418 virtual void Initialize(ASTContext &context);
419
Benjamin Kramer474261a2012-06-02 10:20:41 +0000420 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000421 // rewriting routines on the new ASTs.
422 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
423 Expr **args, unsigned nargs,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000426
427 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000428 QualType returnType,
429 SmallVectorImpl<QualType> &ArgTypes,
430 SmallVectorImpl<Expr*> &MsgExprs,
431 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000432
433 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
434 SourceLocation StartLoc=SourceLocation(),
435 SourceLocation EndLoc=SourceLocation());
436
437 void SynthCountByEnumWithState(std::string &buf);
438 void SynthMsgSendFunctionDecl();
439 void SynthMsgSendSuperFunctionDecl();
440 void SynthMsgSendStretFunctionDecl();
441 void SynthMsgSendFpretFunctionDecl();
442 void SynthMsgSendSuperStretFunctionDecl();
443 void SynthGetClassFunctionDecl();
444 void SynthGetMetaClassFunctionDecl();
445 void SynthGetSuperClassFunctionDecl();
446 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000447 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000448
449 // Rewriting metadata
450 template<typename MethodIterator>
451 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
452 MethodIterator MethodEnd,
453 bool IsInstanceMethod,
454 StringRef prefix,
455 StringRef ClassName,
456 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000457 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
458 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000459 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian11671902012-02-07 17:11:38 +0000460 const ObjCList<ObjCProtocolDecl> &Prots,
461 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000464 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000465
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000466 void RewriteMetaDataIntoBuffer(std::string &Result);
467 void WriteImageInfo(std::string &Result);
468 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000469 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000470 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000471
472 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000473 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000474 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000475 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000476
477
478 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
479 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
480 StringRef funcName, std::string Tag);
481 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
482 StringRef funcName, std::string Tag);
483 std::string SynthesizeBlockImpl(BlockExpr *CE,
484 std::string Tag, std::string Desc);
485 std::string SynthesizeBlockDescriptor(std::string DescTag,
486 std::string ImplTag,
487 int i, StringRef funcName,
488 unsigned hasCopy);
489 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
490 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
491 StringRef FunName);
492 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
493 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000494 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000495
496 // Misc. helper routines.
497 QualType getProtocolType();
498 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000499 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
500 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
501 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
502
503 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
504 void CollectBlockDeclRefInfo(BlockExpr *Exp);
505 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000506 void GetInnerBlockDeclRefExprs(Stmt *S,
507 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000508 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
509
510 // We avoid calling Type::isBlockPointerType(), since it operates on the
511 // canonical type. We only care if the top-level type is a closure pointer.
512 bool isTopLevelBlockPointerType(QualType T) {
513 return isa<BlockPointerType>(T);
514 }
515
516 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
517 /// to a function pointer type and upon success, returns true; false
518 /// otherwise.
519 bool convertBlockPointerToFunctionPointer(QualType &T) {
520 if (isTopLevelBlockPointerType(T)) {
521 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
522 T = Context->getPointerType(BPT->getPointeeType());
523 return true;
524 }
525 return false;
526 }
527
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000528 bool convertObjCTypeToCStyleType(QualType &T);
529
Fariborz Jahanian11671902012-02-07 17:11:38 +0000530 bool needToScanForQualifiers(QualType T);
531 QualType getSuperStructType();
532 QualType getConstantStringStructType();
533 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
534 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
535
536 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000537 if (T->isObjCQualifiedIdType()) {
538 bool isConst = T.isConstQualified();
539 T = isConst ? Context->getObjCIdType().withConst()
540 : Context->getObjCIdType();
541 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000542 else if (T->isObjCQualifiedClassType())
543 T = Context->getObjCClassType();
544 else if (T->isObjCObjectPointerType() &&
545 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
546 if (const ObjCObjectPointerType * OBJPT =
547 T->getAsObjCInterfacePointerType()) {
548 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
549 T = QualType(IFaceT, 0);
550 T = Context->getPointerType(T);
551 }
552 }
553 }
554
555 // FIXME: This predicate seems like it would be useful to add to ASTContext.
556 bool isObjCType(QualType T) {
557 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
558 return false;
559
560 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
561
562 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
563 OCT == Context->getCanonicalType(Context->getObjCClassType()))
564 return true;
565
566 if (const PointerType *PT = OCT->getAs<PointerType>()) {
567 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
568 PT->getPointeeType()->isObjCQualifiedIdType())
569 return true;
570 }
571 return false;
572 }
573 bool PointerTypeTakesAnyBlockArguments(QualType QT);
574 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
575 void GetExtentOfArgList(const char *Name, const char *&LParen,
576 const char *&RParen);
577
578 void QuoteDoublequotes(std::string &From, std::string &To) {
579 for (unsigned i = 0; i < From.length(); i++) {
580 if (From[i] == '"')
581 To += "\\\"";
582 else
583 To += From[i];
584 }
585 }
586
587 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000588 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000589 bool variadic = false) {
590 if (result == Context->getObjCInstanceType())
591 result = Context->getObjCIdType();
592 FunctionProtoType::ExtProtoInfo fpi;
593 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000594 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000595 }
596
597 // Helper function: create a CStyleCastExpr with trivial type source info.
598 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
599 CastKind Kind, Expr *E) {
600 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
601 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
602 SourceLocation(), SourceLocation());
603 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000604
605 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
606 IdentifierInfo* II = &Context->Idents.get("load");
607 Selector LoadSel = Context->Selectors.getSelector(0, &II);
608 return OD->getClassMethod(LoadSel) != 0;
609 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000610
611 StringLiteral *getStringLiteral(StringRef Str) {
612 QualType StrType = Context->getConstantArrayType(
613 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
614 0);
615 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
616 /*Pascal=*/false, StrType, SourceLocation());
617 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000618 };
619
620}
621
622void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
623 NamedDecl *D) {
624 if (const FunctionProtoType *fproto
625 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000626 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
627 E = fproto->param_type_end();
628 I && (I != E); ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000629 if (isTopLevelBlockPointerType(*I)) {
630 // All the args are checked/rewritten. Don't call twice!
631 RewriteBlockPointerDecl(D);
632 break;
633 }
634 }
635}
636
637void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
638 const PointerType *PT = funcType->getAs<PointerType>();
639 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
640 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
641}
642
643static bool IsHeaderFile(const std::string &Filename) {
644 std::string::size_type DotPos = Filename.rfind('.');
645
646 if (DotPos == std::string::npos) {
647 // no file extension
648 return false;
649 }
650
651 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
652 // C header: .h
653 // C++ header: .hh or .H;
654 return Ext == "h" || Ext == "hh" || Ext == "H";
655}
656
657RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
658 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000659 bool silenceMacroWarn,
660 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000661 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000662 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000663 IsHeader = IsHeaderFile(inFile);
664 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
665 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000666 // FIXME. This should be an error. But if block is not called, it is OK. And it
667 // may break including some headers.
668 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
669 "rewriting block literal declared in global scope is not implemented");
670
Fariborz Jahanian11671902012-02-07 17:11:38 +0000671 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
672 DiagnosticsEngine::Warning,
673 "rewriter doesn't support user-specified control flow semantics "
674 "for @try/@finally (code may not execute properly)");
675}
676
677ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
678 raw_ostream* OS,
679 DiagnosticsEngine &Diags,
680 const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000681 bool SilenceRewriteMacroWarning,
682 bool LineInfo) {
683 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
684 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000685}
686
687void RewriteModernObjC::InitializeCommon(ASTContext &context) {
688 Context = &context;
689 SM = &Context->getSourceManager();
690 TUDecl = Context->getTranslationUnitDecl();
691 MsgSendFunctionDecl = 0;
692 MsgSendSuperFunctionDecl = 0;
693 MsgSendStretFunctionDecl = 0;
694 MsgSendSuperStretFunctionDecl = 0;
695 MsgSendFpretFunctionDecl = 0;
696 GetClassFunctionDecl = 0;
697 GetMetaClassFunctionDecl = 0;
698 GetSuperClassFunctionDecl = 0;
699 SelGetUidFunctionDecl = 0;
700 CFStringFunctionDecl = 0;
701 ConstantStringClassReference = 0;
702 NSStringRecord = 0;
703 CurMethodDef = 0;
704 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000705 GlobalVarDecl = 0;
Fariborz Jahaniane0050702012-03-23 00:00:49 +0000706 GlobalConstructionExp = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000707 SuperStructDecl = 0;
708 ProtocolTypeDecl = 0;
709 ConstantStringDecl = 0;
710 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000711 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000712 NumObjCStringLiterals = 0;
713 PropParentMap = 0;
714 CurrentBody = 0;
715 DisableReplaceStmt = false;
716 objc_impl_method = false;
717
718 // Get the ID and start/end of the main file.
719 MainFileID = SM->getMainFileID();
720 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
721 MainFileStart = MainBuf->getBufferStart();
722 MainFileEnd = MainBuf->getBufferEnd();
723
David Blaikiebbafb8a2012-03-11 07:00:24 +0000724 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000725}
726
727//===----------------------------------------------------------------------===//
728// Top Level Driver Code
729//===----------------------------------------------------------------------===//
730
731void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
732 if (Diags.hasErrorOccurred())
733 return;
734
735 // Two cases: either the decl could be in the main file, or it could be in a
736 // #included file. If the former, rewrite it now. If the later, check to see
737 // if we rewrote the #include/#import.
738 SourceLocation Loc = D->getLocation();
739 Loc = SM->getExpansionLoc(Loc);
740
741 // If this is for a builtin, ignore it.
742 if (Loc.isInvalid()) return;
743
744 // Look for built-in declarations that we need to refer during the rewrite.
745 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
746 RewriteFunctionDecl(FD);
747 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
748 // declared in <Foundation/NSString.h>
749 if (FVD->getName() == "_NSConstantStringClassReference") {
750 ConstantStringClassReference = FVD;
751 return;
752 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000753 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
754 RewriteCategoryDecl(CD);
755 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
756 if (PD->isThisDeclarationADefinition())
757 RewriteProtocolDecl(PD);
758 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000759 // FIXME. This will not work in all situations and leaving it out
760 // is harmless.
761 // RewriteLinkageSpec(LSD);
762
Fariborz Jahanian11671902012-02-07 17:11:38 +0000763 // Recurse into linkage specifications
764 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
765 DIEnd = LSD->decls_end();
766 DI != DIEnd; ) {
767 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
768 if (!IFace->isThisDeclarationADefinition()) {
769 SmallVector<Decl *, 8> DG;
770 SourceLocation StartLoc = IFace->getLocStart();
771 do {
772 if (isa<ObjCInterfaceDecl>(*DI) &&
773 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
774 StartLoc == (*DI)->getLocStart())
775 DG.push_back(*DI);
776 else
777 break;
778
779 ++DI;
780 } while (DI != DIEnd);
781 RewriteForwardClassDecl(DG);
782 continue;
783 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000784 else {
785 // Keep track of all interface declarations seen.
786 ObjCInterfacesSeen.push_back(IFace);
787 ++DI;
788 continue;
789 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000790 }
791
792 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
793 if (!Proto->isThisDeclarationADefinition()) {
794 SmallVector<Decl *, 8> DG;
795 SourceLocation StartLoc = Proto->getLocStart();
796 do {
797 if (isa<ObjCProtocolDecl>(*DI) &&
798 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
799 StartLoc == (*DI)->getLocStart())
800 DG.push_back(*DI);
801 else
802 break;
803
804 ++DI;
805 } while (DI != DIEnd);
806 RewriteForwardProtocolDecl(DG);
807 continue;
808 }
809 }
810
811 HandleTopLevelSingleDecl(*DI);
812 ++DI;
813 }
814 }
815 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000816 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000817 return HandleDeclInMainFile(D);
818}
819
820//===----------------------------------------------------------------------===//
821// Syntactic (non-AST) Rewriting Code
822//===----------------------------------------------------------------------===//
823
824void RewriteModernObjC::RewriteInclude() {
825 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
826 StringRef MainBuf = SM->getBufferData(MainFileID);
827 const char *MainBufStart = MainBuf.begin();
828 const char *MainBufEnd = MainBuf.end();
829 size_t ImportLen = strlen("import");
830
831 // Loop over the whole file, looking for includes.
832 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
833 if (*BufPtr == '#') {
834 if (++BufPtr == MainBufEnd)
835 return;
836 while (*BufPtr == ' ' || *BufPtr == '\t')
837 if (++BufPtr == MainBufEnd)
838 return;
839 if (!strncmp(BufPtr, "import", ImportLen)) {
840 // replace import with include
841 SourceLocation ImportLoc =
842 LocStart.getLocWithOffset(BufPtr-MainBufStart);
843 ReplaceText(ImportLoc, ImportLen, "include");
844 BufPtr += ImportLen;
845 }
846 }
847 }
848}
849
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000850static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
851 ObjCIvarDecl *IvarDecl, std::string &Result) {
852 Result += "OBJC_IVAR_$_";
853 Result += IDecl->getName();
854 Result += "$";
855 Result += IvarDecl->getName();
856}
857
858std::string
859RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
860 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
861
862 // Build name of symbol holding ivar offset.
863 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000864 if (D->isBitField())
865 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
866 else
867 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000868
869
870 std::string S = "(*(";
871 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000872 if (D->isBitField())
873 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000874
875 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
876 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
877 RD = RD->getDefinition();
878 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
879 // decltype(((Foo_IMPL*)0)->bar) *
880 ObjCContainerDecl *CDecl =
881 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
882 // ivar in class extensions requires special treatment.
883 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
884 CDecl = CatDecl->getClassInterface();
885 std::string RecName = CDecl->getName();
886 RecName += "_IMPL";
887 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
888 SourceLocation(), SourceLocation(),
889 &Context->Idents.get(RecName.c_str()));
890 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
891 unsigned UnsignedIntSize =
892 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
893 Expr *Zero = IntegerLiteral::Create(*Context,
894 llvm::APInt(UnsignedIntSize, 0),
895 Context->UnsignedIntTy, SourceLocation());
896 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
897 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
898 Zero);
899 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
900 SourceLocation(),
901 &Context->Idents.get(D->getNameAsString()),
902 IvarT, 0,
903 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +0000904 ICIS_NoInit);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000905 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
906 FD->getType(), VK_LValue,
907 OK_Ordinary);
908 IvarT = Context->getDecltypeType(ME, ME->getType());
909 }
910 }
911 convertObjCTypeToCStyleType(IvarT);
912 QualType castT = Context->getPointerType(IvarT);
913 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
914 S += TypeString;
915 S += ")";
916
917 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
918 S += "((char *)self + ";
919 S += IvarOffsetName;
920 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000921 if (D->isBitField()) {
922 S += ".";
923 S += D->getNameAsString();
924 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000925 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000926 return S;
927}
928
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000929/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
930/// been found in the class implementation. In this case, it must be synthesized.
931static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
932 ObjCPropertyDecl *PD,
933 bool getter) {
934 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
935 : !IMP->getInstanceMethod(PD->getSetterName());
936
937}
938
Fariborz Jahanian11671902012-02-07 17:11:38 +0000939void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
940 ObjCImplementationDecl *IMD,
941 ObjCCategoryImplDecl *CID) {
942 static bool objcGetPropertyDefined = false;
943 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000944 SourceLocation startGetterSetterLoc;
945
946 if (PID->getLocStart().isValid()) {
947 SourceLocation startLoc = PID->getLocStart();
948 InsertText(startLoc, "// ");
949 const char *startBuf = SM->getCharacterData(startLoc);
950 assert((*startBuf == '@') && "bogus @synthesize location");
951 const char *semiBuf = strchr(startBuf, ';');
952 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
953 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
954 }
955 else
956 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957
958 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
959 return; // FIXME: is this correct?
960
961 // Generate the 'getter' function.
962 ObjCPropertyDecl *PD = PID->getPropertyDecl();
963 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000964 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000965
Bill Wendling44426052012-12-20 19:22:21 +0000966 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000967 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000968 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
969 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000970 ObjCPropertyDecl::OBJC_PR_copy));
971 std::string Getr;
972 if (GenGetProperty && !objcGetPropertyDefined) {
973 objcGetPropertyDefined = true;
974 // FIXME. Is this attribute correct in all cases?
975 Getr = "\nextern \"C\" __declspec(dllimport) "
976 "id objc_getProperty(id, SEL, long, bool);\n";
977 }
978 RewriteObjCMethodDecl(OID->getContainingInterface(),
979 PD->getGetterMethodDecl(), Getr);
980 Getr += "{ ";
981 // Synthesize an explicit cast to gain access to the ivar.
982 // See objc-act.c:objc_synthesize_new_getter() for details.
983 if (GenGetProperty) {
984 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
985 Getr += "typedef ";
986 const FunctionType *FPRetType = 0;
Alp Toker314cc812014-01-25 16:55:45 +0000987 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000988 FPRetType);
989 Getr += " _TYPE";
990 if (FPRetType) {
991 Getr += ")"; // close the precedence "scope" for "*".
992
993 // Now, emit the argument types (if any).
994 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
995 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000996 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000997 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000998 std::string ParamStr =
999 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001000 Getr += ParamStr;
1001 }
1002 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001003 if (FT->getNumParams())
1004 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001005 Getr += "...";
1006 }
1007 Getr += ")";
1008 } else
1009 Getr += "()";
1010 }
1011 Getr += ";\n";
1012 Getr += "return (_TYPE)";
1013 Getr += "objc_getProperty(self, _cmd, ";
1014 RewriteIvarOffsetComputation(OID, Getr);
1015 Getr += ", 1)";
1016 }
1017 else
1018 Getr += "return " + getIvarAccessString(OID);
1019 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001020 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001021 }
1022
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001023 if (PD->isReadOnly() ||
1024 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001025 return;
1026
1027 // Generate the 'setter' function.
1028 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001029 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001030 ObjCPropertyDecl::OBJC_PR_copy);
1031 if (GenSetProperty && !objcSetPropertyDefined) {
1032 objcSetPropertyDefined = true;
1033 // FIXME. Is this attribute correct in all cases?
1034 Setr = "\nextern \"C\" __declspec(dllimport) "
1035 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1036 }
1037
1038 RewriteObjCMethodDecl(OID->getContainingInterface(),
1039 PD->getSetterMethodDecl(), Setr);
1040 Setr += "{ ";
1041 // Synthesize an explicit cast to initialize the ivar.
1042 // See objc-act.c:objc_synthesize_new_setter() for details.
1043 if (GenSetProperty) {
1044 Setr += "objc_setProperty (self, _cmd, ";
1045 RewriteIvarOffsetComputation(OID, Setr);
1046 Setr += ", (id)";
1047 Setr += PD->getName();
1048 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001049 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001050 Setr += "0, ";
1051 else
1052 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001053 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001054 Setr += "1)";
1055 else
1056 Setr += "0)";
1057 }
1058 else {
1059 Setr += getIvarAccessString(OID) + " = ";
1060 Setr += PD->getName();
1061 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001062 Setr += "; }\n";
1063 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001064}
1065
1066static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1067 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001068 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001069 typedefString += ForwardDecl->getNameAsString();
1070 typedefString += "\n";
1071 typedefString += "#define _REWRITER_typedef_";
1072 typedefString += ForwardDecl->getNameAsString();
1073 typedefString += "\n";
1074 typedefString += "typedef struct objc_object ";
1075 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001076 // typedef struct { } _objc_exc_Classname;
1077 typedefString += ";\ntypedef struct {} _objc_exc_";
1078 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001079 typedefString += ";\n#endif\n";
1080}
1081
1082void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1083 const std::string &typedefString) {
1084 SourceLocation startLoc = ClassDecl->getLocStart();
1085 const char *startBuf = SM->getCharacterData(startLoc);
1086 const char *semiPtr = strchr(startBuf, ';');
1087 // Replace the @class with typedefs corresponding to the classes.
1088 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1089}
1090
1091void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1092 std::string typedefString;
1093 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001094 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1095 if (I == D.begin()) {
1096 // Translate to typedef's that forward reference structs with the same name
1097 // as the class. As a convenience, we include the original declaration
1098 // as a comment.
1099 typedefString += "// @class ";
1100 typedefString += ForwardDecl->getNameAsString();
1101 typedefString += ";";
1102 }
1103 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001104 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001105 else
1106 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001107 }
1108 DeclGroupRef::iterator I = D.begin();
1109 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1110}
1111
1112void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001113 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001114 std::string typedefString;
1115 for (unsigned i = 0; i < D.size(); i++) {
1116 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1117 if (i == 0) {
1118 typedefString += "// @class ";
1119 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001120 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001121 }
1122 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1123 }
1124 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1125}
1126
1127void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1128 // When method is a synthesized one, such as a getter/setter there is
1129 // nothing to rewrite.
1130 if (Method->isImplicit())
1131 return;
1132 SourceLocation LocStart = Method->getLocStart();
1133 SourceLocation LocEnd = Method->getLocEnd();
1134
1135 if (SM->getExpansionLineNumber(LocEnd) >
1136 SM->getExpansionLineNumber(LocStart)) {
1137 InsertText(LocStart, "#if 0\n");
1138 ReplaceText(LocEnd, 1, ";\n#endif\n");
1139 } else {
1140 InsertText(LocStart, "// ");
1141 }
1142}
1143
1144void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1145 SourceLocation Loc = prop->getAtLoc();
1146
1147 ReplaceText(Loc, 0, "// ");
1148 // FIXME: handle properties that are declared across multiple lines.
1149}
1150
1151void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1152 SourceLocation LocStart = CatDecl->getLocStart();
1153
1154 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001155 if (CatDecl->getIvarRBraceLoc().isValid()) {
1156 ReplaceText(LocStart, 1, "/** ");
1157 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1158 }
1159 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001160 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001161 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001162
Aaron Ballmand174edf2014-03-13 19:11:50 +00001163 for (auto *I : CatDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001164 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001165
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001166 for (auto *I : CatDecl->instance_methods())
1167 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001168 for (auto *I : CatDecl->class_methods())
1169 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001170
1171 // Lastly, comment out the @end.
1172 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001173 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001174}
1175
1176void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1177 SourceLocation LocStart = PDecl->getLocStart();
1178 assert(PDecl->isThisDeclarationADefinition());
1179
1180 // FIXME: handle protocol headers that are declared across multiple lines.
1181 ReplaceText(LocStart, 0, "// ");
1182
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001183 for (auto *I : PDecl->instance_methods())
1184 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001185 for (auto *I : PDecl->class_methods())
1186 RewriteMethodDeclaration(I);
Aaron Ballmand174edf2014-03-13 19:11:50 +00001187 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001188 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001189
1190 // Lastly, comment out the @end.
1191 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001192 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001193
1194 // Must comment out @optional/@required
1195 const char *startBuf = SM->getCharacterData(LocStart);
1196 const char *endBuf = SM->getCharacterData(LocEnd);
1197 for (const char *p = startBuf; p < endBuf; p++) {
1198 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1199 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1200 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1201
1202 }
1203 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1204 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1205 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1206
1207 }
1208 }
1209}
1210
1211void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1212 SourceLocation LocStart = (*D.begin())->getLocStart();
1213 if (LocStart.isInvalid())
1214 llvm_unreachable("Invalid SourceLocation");
1215 // FIXME: handle forward protocol that are declared across multiple lines.
1216 ReplaceText(LocStart, 0, "// ");
1217}
1218
1219void
Craig Topper5603df42013-07-05 19:34:19 +00001220RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001221 SourceLocation LocStart = DG[0]->getLocStart();
1222 if (LocStart.isInvalid())
1223 llvm_unreachable("Invalid SourceLocation");
1224 // FIXME: handle forward protocol that are declared across multiple lines.
1225 ReplaceText(LocStart, 0, "// ");
1226}
1227
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001228void
1229RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1230 SourceLocation LocStart = LSD->getExternLoc();
1231 if (LocStart.isInvalid())
1232 llvm_unreachable("Invalid extern SourceLocation");
1233
1234 ReplaceText(LocStart, 0, "// ");
1235 if (!LSD->hasBraces())
1236 return;
1237 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1238 SourceLocation LocRBrace = LSD->getRBraceLoc();
1239 if (LocRBrace.isInvalid())
1240 llvm_unreachable("Invalid rbrace SourceLocation");
1241 ReplaceText(LocRBrace, 0, "// ");
1242}
1243
Fariborz Jahanian11671902012-02-07 17:11:38 +00001244void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1245 const FunctionType *&FPRetType) {
1246 if (T->isObjCQualifiedIdType())
1247 ResultStr += "id";
1248 else if (T->isFunctionPointerType() ||
1249 T->isBlockPointerType()) {
1250 // needs special handling, since pointer-to-functions have special
1251 // syntax (where a decaration models use).
1252 QualType retType = T;
1253 QualType PointeeTy;
1254 if (const PointerType* PT = retType->getAs<PointerType>())
1255 PointeeTy = PT->getPointeeType();
1256 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1257 PointeeTy = BPT->getPointeeType();
1258 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001259 ResultStr +=
1260 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001261 ResultStr += "(*";
1262 }
1263 } else
1264 ResultStr += T.getAsString(Context->getPrintingPolicy());
1265}
1266
1267void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1268 ObjCMethodDecl *OMD,
1269 std::string &ResultStr) {
1270 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1271 const FunctionType *FPRetType = 0;
1272 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001273 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001274 ResultStr += " ";
1275
1276 // Unique method name
1277 std::string NameStr;
1278
1279 if (OMD->isInstanceMethod())
1280 NameStr += "_I_";
1281 else
1282 NameStr += "_C_";
1283
1284 NameStr += IDecl->getNameAsString();
1285 NameStr += "_";
1286
1287 if (ObjCCategoryImplDecl *CID =
1288 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1289 NameStr += CID->getNameAsString();
1290 NameStr += "_";
1291 }
1292 // Append selector names, replacing ':' with '_'
1293 {
1294 std::string selString = OMD->getSelector().getAsString();
1295 int len = selString.size();
1296 for (int i = 0; i < len; i++)
1297 if (selString[i] == ':')
1298 selString[i] = '_';
1299 NameStr += selString;
1300 }
1301 // Remember this name for metadata emission
1302 MethodInternalNames[OMD] = NameStr;
1303 ResultStr += NameStr;
1304
1305 // Rewrite arguments
1306 ResultStr += "(";
1307
1308 // invisible arguments
1309 if (OMD->isInstanceMethod()) {
1310 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1311 selfTy = Context->getPointerType(selfTy);
1312 if (!LangOpts.MicrosoftExt) {
1313 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1314 ResultStr += "struct ";
1315 }
1316 // When rewriting for Microsoft, explicitly omit the structure name.
1317 ResultStr += IDecl->getNameAsString();
1318 ResultStr += " *";
1319 }
1320 else
1321 ResultStr += Context->getObjCClassType().getAsString(
1322 Context->getPrintingPolicy());
1323
1324 ResultStr += " self, ";
1325 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1326 ResultStr += " _cmd";
1327
1328 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001329 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001330 ResultStr += ", ";
1331 if (PDecl->getType()->isObjCQualifiedIdType()) {
1332 ResultStr += "id ";
1333 ResultStr += PDecl->getNameAsString();
1334 } else {
1335 std::string Name = PDecl->getNameAsString();
1336 QualType QT = PDecl->getType();
1337 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001338 (void)convertBlockPointerToFunctionPointer(QT);
1339 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001340 ResultStr += Name;
1341 }
1342 }
1343 if (OMD->isVariadic())
1344 ResultStr += ", ...";
1345 ResultStr += ") ";
1346
1347 if (FPRetType) {
1348 ResultStr += ")"; // close the precedence "scope" for "*".
1349
1350 // Now, emit the argument types (if any).
1351 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1352 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001353 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001354 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001355 std::string ParamStr =
1356 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001357 ResultStr += ParamStr;
1358 }
1359 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001360 if (FT->getNumParams())
1361 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001362 ResultStr += "...";
1363 }
1364 ResultStr += ")";
1365 } else {
1366 ResultStr += "()";
1367 }
1368 }
1369}
1370void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1371 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1372 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1373
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001374 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001375 if (IMD->getIvarRBraceLoc().isValid()) {
1376 ReplaceText(IMD->getLocStart(), 1, "/** ");
1377 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001378 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001379 else {
1380 InsertText(IMD->getLocStart(), "// ");
1381 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001382 }
1383 else
1384 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001385
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001386 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001387 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001388 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1389 SourceLocation LocStart = OMD->getLocStart();
1390 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1391
1392 const char *startBuf = SM->getCharacterData(LocStart);
1393 const char *endBuf = SM->getCharacterData(LocEnd);
1394 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1395 }
1396
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001397 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001398 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001399 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1400 SourceLocation LocStart = OMD->getLocStart();
1401 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1402
1403 const char *startBuf = SM->getCharacterData(LocStart);
1404 const char *endBuf = SM->getCharacterData(LocEnd);
1405 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1406 }
1407 for (ObjCCategoryImplDecl::propimpl_iterator
1408 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1409 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1410 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001411 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001412 }
1413
1414 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1415}
1416
1417void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001418 // Do not synthesize more than once.
1419 if (ObjCSynthesizedStructs.count(ClassDecl))
1420 return;
1421 // Make sure super class's are written before current class is written.
1422 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1423 while (SuperClass) {
1424 RewriteInterfaceDecl(SuperClass);
1425 SuperClass = SuperClass->getSuperClass();
1426 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001427 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001428 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001429 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001430 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001431 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1432
Fariborz Jahanianff513382012-02-15 22:01:47 +00001433 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001434 // Mark this typedef as having been written into its c++ equivalent.
1435 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001436
Aaron Ballmand174edf2014-03-13 19:11:50 +00001437 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001438 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001439 for (auto *I : ClassDecl->instance_methods())
1440 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001441 for (auto *I : ClassDecl->class_methods())
1442 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001443
Fariborz Jahanianff513382012-02-15 22:01:47 +00001444 // Lastly, comment out the @end.
1445 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001446 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001447 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001448}
1449
1450Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1451 SourceRange OldRange = PseudoOp->getSourceRange();
1452
1453 // We just magically know some things about the structure of this
1454 // expression.
1455 ObjCMessageExpr *OldMsg =
1456 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1457 PseudoOp->getNumSemanticExprs() - 1));
1458
1459 // Because the rewriter doesn't allow us to rewrite rewritten code,
1460 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001461 Expr *Base;
1462 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001463 {
1464 DisableReplaceStmtScope S(*this);
1465
1466 // Rebuild the base expression if we have one.
1467 Base = 0;
1468 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1469 Base = OldMsg->getInstanceReceiver();
1470 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1471 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1472 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001473
1474 unsigned numArgs = OldMsg->getNumArgs();
1475 for (unsigned i = 0; i < numArgs; i++) {
1476 Expr *Arg = OldMsg->getArg(i);
1477 if (isa<OpaqueValueExpr>(Arg))
1478 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1479 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1480 Args.push_back(Arg);
1481 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001482 }
1483
1484 // TODO: avoid this copy.
1485 SmallVector<SourceLocation, 1> SelLocs;
1486 OldMsg->getSelectorLocs(SelLocs);
1487
1488 ObjCMessageExpr *NewMsg = 0;
1489 switch (OldMsg->getReceiverKind()) {
1490 case ObjCMessageExpr::Class:
1491 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1492 OldMsg->getValueKind(),
1493 OldMsg->getLeftLoc(),
1494 OldMsg->getClassReceiverTypeInfo(),
1495 OldMsg->getSelector(),
1496 SelLocs,
1497 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001498 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001499 OldMsg->getRightLoc(),
1500 OldMsg->isImplicit());
1501 break;
1502
1503 case ObjCMessageExpr::Instance:
1504 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1505 OldMsg->getValueKind(),
1506 OldMsg->getLeftLoc(),
1507 Base,
1508 OldMsg->getSelector(),
1509 SelLocs,
1510 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001511 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001512 OldMsg->getRightLoc(),
1513 OldMsg->isImplicit());
1514 break;
1515
1516 case ObjCMessageExpr::SuperClass:
1517 case ObjCMessageExpr::SuperInstance:
1518 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1519 OldMsg->getValueKind(),
1520 OldMsg->getLeftLoc(),
1521 OldMsg->getSuperLoc(),
1522 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1523 OldMsg->getSuperType(),
1524 OldMsg->getSelector(),
1525 SelLocs,
1526 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001527 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001528 OldMsg->getRightLoc(),
1529 OldMsg->isImplicit());
1530 break;
1531 }
1532
1533 Stmt *Replacement = SynthMessageExpr(NewMsg);
1534 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1535 return Replacement;
1536}
1537
1538Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1539 SourceRange OldRange = PseudoOp->getSourceRange();
1540
1541 // We just magically know some things about the structure of this
1542 // expression.
1543 ObjCMessageExpr *OldMsg =
1544 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1545
1546 // Because the rewriter doesn't allow us to rewrite rewritten code,
1547 // we need to suppress rewriting the sub-statements.
1548 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001549 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001550 {
1551 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001552 // Rebuild the base expression if we have one.
1553 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1554 Base = OldMsg->getInstanceReceiver();
1555 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1556 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1557 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001558 unsigned numArgs = OldMsg->getNumArgs();
1559 for (unsigned i = 0; i < numArgs; i++) {
1560 Expr *Arg = OldMsg->getArg(i);
1561 if (isa<OpaqueValueExpr>(Arg))
1562 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1563 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1564 Args.push_back(Arg);
1565 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001566 }
1567
1568 // Intentionally empty.
1569 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001570
1571 ObjCMessageExpr *NewMsg = 0;
1572 switch (OldMsg->getReceiverKind()) {
1573 case ObjCMessageExpr::Class:
1574 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1575 OldMsg->getValueKind(),
1576 OldMsg->getLeftLoc(),
1577 OldMsg->getClassReceiverTypeInfo(),
1578 OldMsg->getSelector(),
1579 SelLocs,
1580 OldMsg->getMethodDecl(),
1581 Args,
1582 OldMsg->getRightLoc(),
1583 OldMsg->isImplicit());
1584 break;
1585
1586 case ObjCMessageExpr::Instance:
1587 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1588 OldMsg->getValueKind(),
1589 OldMsg->getLeftLoc(),
1590 Base,
1591 OldMsg->getSelector(),
1592 SelLocs,
1593 OldMsg->getMethodDecl(),
1594 Args,
1595 OldMsg->getRightLoc(),
1596 OldMsg->isImplicit());
1597 break;
1598
1599 case ObjCMessageExpr::SuperClass:
1600 case ObjCMessageExpr::SuperInstance:
1601 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1602 OldMsg->getValueKind(),
1603 OldMsg->getLeftLoc(),
1604 OldMsg->getSuperLoc(),
1605 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1606 OldMsg->getSuperType(),
1607 OldMsg->getSelector(),
1608 SelLocs,
1609 OldMsg->getMethodDecl(),
1610 Args,
1611 OldMsg->getRightLoc(),
1612 OldMsg->isImplicit());
1613 break;
1614 }
1615
1616 Stmt *Replacement = SynthMessageExpr(NewMsg);
1617 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1618 return Replacement;
1619}
1620
1621/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001622/// ((NSUInteger (*)
1623/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001624/// (void *)objc_msgSend)((id)l_collection,
1625/// sel_registerName(
1626/// "countByEnumeratingWithState:objects:count:"),
1627/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001628/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001629///
1630void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001631 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1632 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001633 buf += "\n\t\t";
1634 buf += "((id)l_collection,\n\t\t";
1635 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1636 buf += "\n\t\t";
1637 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001638 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001639}
1640
1641/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1642/// statement to exit to its outer synthesized loop.
1643///
1644Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1645 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1646 return S;
1647 // replace break with goto __break_label
1648 std::string buf;
1649
1650 SourceLocation startLoc = S->getLocStart();
1651 buf = "goto __break_label_";
1652 buf += utostr(ObjCBcLabelNo.back());
1653 ReplaceText(startLoc, strlen("break"), buf);
1654
1655 return 0;
1656}
1657
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001658void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1659 SourceLocation Loc,
1660 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001661 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001662 LineString += "\n#line ";
1663 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1664 LineString += utostr(PLoc.getLine());
1665 LineString += " \"";
1666 LineString += Lexer::Stringify(PLoc.getFilename());
1667 LineString += "\"\n";
1668 }
1669}
1670
Fariborz Jahanian11671902012-02-07 17:11:38 +00001671/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1672/// statement to continue with its inner synthesized loop.
1673///
1674Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1675 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1676 return S;
1677 // replace continue with goto __continue_label
1678 std::string buf;
1679
1680 SourceLocation startLoc = S->getLocStart();
1681 buf = "goto __continue_label_";
1682 buf += utostr(ObjCBcLabelNo.back());
1683 ReplaceText(startLoc, strlen("continue"), buf);
1684
1685 return 0;
1686}
1687
1688/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1689/// It rewrites:
1690/// for ( type elem in collection) { stmts; }
1691
1692/// Into:
1693/// {
1694/// type elem;
1695/// struct __objcFastEnumerationState enumState = { 0 };
1696/// id __rw_items[16];
1697/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001698/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001699/// objects:__rw_items count:16];
1700/// if (limit) {
1701/// unsigned long startMutations = *enumState.mutationsPtr;
1702/// do {
1703/// unsigned long counter = 0;
1704/// do {
1705/// if (startMutations != *enumState.mutationsPtr)
1706/// objc_enumerationMutation(l_collection);
1707/// elem = (type)enumState.itemsPtr[counter++];
1708/// stmts;
1709/// __continue_label: ;
1710/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001711/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1712/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001713/// elem = nil;
1714/// __break_label: ;
1715/// }
1716/// else
1717/// elem = nil;
1718/// }
1719///
1720Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1721 SourceLocation OrigEnd) {
1722 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1723 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1724 "ObjCForCollectionStmt Statement stack mismatch");
1725 assert(!ObjCBcLabelNo.empty() &&
1726 "ObjCForCollectionStmt - Label No stack empty");
1727
1728 SourceLocation startLoc = S->getLocStart();
1729 const char *startBuf = SM->getCharacterData(startLoc);
1730 StringRef elementName;
1731 std::string elementTypeAsString;
1732 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001733 // line directive first.
1734 SourceLocation ForEachLoc = S->getForLoc();
1735 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1736 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001737 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1738 // type elem;
1739 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1740 QualType ElementType = cast<ValueDecl>(D)->getType();
1741 if (ElementType->isObjCQualifiedIdType() ||
1742 ElementType->isObjCQualifiedInterfaceType())
1743 // Simply use 'id' for all qualified types.
1744 elementTypeAsString = "id";
1745 else
1746 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1747 buf += elementTypeAsString;
1748 buf += " ";
1749 elementName = D->getName();
1750 buf += elementName;
1751 buf += ";\n\t";
1752 }
1753 else {
1754 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1755 elementName = DR->getDecl()->getName();
1756 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1757 if (VD->getType()->isObjCQualifiedIdType() ||
1758 VD->getType()->isObjCQualifiedInterfaceType())
1759 // Simply use 'id' for all qualified types.
1760 elementTypeAsString = "id";
1761 else
1762 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1763 }
1764
1765 // struct __objcFastEnumerationState enumState = { 0 };
1766 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1767 // id __rw_items[16];
1768 buf += "id __rw_items[16];\n\t";
1769 // id l_collection = (id)
1770 buf += "id l_collection = (id)";
1771 // Find start location of 'collection' the hard way!
1772 const char *startCollectionBuf = startBuf;
1773 startCollectionBuf += 3; // skip 'for'
1774 startCollectionBuf = strchr(startCollectionBuf, '(');
1775 startCollectionBuf++; // skip '('
1776 // find 'in' and skip it.
1777 while (*startCollectionBuf != ' ' ||
1778 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1779 (*(startCollectionBuf+3) != ' ' &&
1780 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1781 startCollectionBuf++;
1782 startCollectionBuf += 3;
1783
1784 // Replace: "for (type element in" with string constructed thus far.
1785 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1786 // Replace ')' in for '(' type elem in collection ')' with ';'
1787 SourceLocation rightParenLoc = S->getRParenLoc();
1788 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1789 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1790 buf = ";\n\t";
1791
1792 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1793 // objects:__rw_items count:16];
1794 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001795 // NSUInteger limit =
1796 // ((NSUInteger (*)
1797 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001798 // (void *)objc_msgSend)((id)l_collection,
1799 // sel_registerName(
1800 // "countByEnumeratingWithState:objects:count:"),
1801 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001802 // (id *)__rw_items, (NSUInteger)16);
1803 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001804 SynthCountByEnumWithState(buf);
1805 buf += ";\n\t";
1806 /// if (limit) {
1807 /// unsigned long startMutations = *enumState.mutationsPtr;
1808 /// do {
1809 /// unsigned long counter = 0;
1810 /// do {
1811 /// if (startMutations != *enumState.mutationsPtr)
1812 /// objc_enumerationMutation(l_collection);
1813 /// elem = (type)enumState.itemsPtr[counter++];
1814 buf += "if (limit) {\n\t";
1815 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1816 buf += "do {\n\t\t";
1817 buf += "unsigned long counter = 0;\n\t\t";
1818 buf += "do {\n\t\t\t";
1819 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1820 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1821 buf += elementName;
1822 buf += " = (";
1823 buf += elementTypeAsString;
1824 buf += ")enumState.itemsPtr[counter++];";
1825 // Replace ')' in for '(' type elem in collection ')' with all of these.
1826 ReplaceText(lparenLoc, 1, buf);
1827
1828 /// __continue_label: ;
1829 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001830 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1831 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001832 /// elem = nil;
1833 /// __break_label: ;
1834 /// }
1835 /// else
1836 /// elem = nil;
1837 /// }
1838 ///
1839 buf = ";\n\t";
1840 buf += "__continue_label_";
1841 buf += utostr(ObjCBcLabelNo.back());
1842 buf += ": ;";
1843 buf += "\n\t\t";
1844 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001845 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001846 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001847 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001848 buf += elementName;
1849 buf += " = ((";
1850 buf += elementTypeAsString;
1851 buf += ")0);\n\t";
1852 buf += "__break_label_";
1853 buf += utostr(ObjCBcLabelNo.back());
1854 buf += ": ;\n\t";
1855 buf += "}\n\t";
1856 buf += "else\n\t\t";
1857 buf += elementName;
1858 buf += " = ((";
1859 buf += elementTypeAsString;
1860 buf += ")0);\n\t";
1861 buf += "}\n";
1862
1863 // Insert all these *after* the statement body.
1864 // FIXME: If this should support Obj-C++, support CXXTryStmt
1865 if (isa<CompoundStmt>(S->getBody())) {
1866 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1867 InsertText(endBodyLoc, buf);
1868 } else {
1869 /* Need to treat single statements specially. For example:
1870 *
1871 * for (A *a in b) if (stuff()) break;
1872 * for (A *a in b) xxxyy;
1873 *
1874 * The following code simply scans ahead to the semi to find the actual end.
1875 */
1876 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1877 const char *semiBuf = strchr(stmtBuf, ';');
1878 assert(semiBuf && "Can't find ';'");
1879 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1880 InsertText(endBodyLoc, buf);
1881 }
1882 Stmts.pop_back();
1883 ObjCBcLabelNo.pop_back();
1884 return 0;
1885}
1886
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001887static void Write_RethrowObject(std::string &buf) {
1888 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1889 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1890 buf += "\tid rethrow;\n";
1891 buf += "\t} _fin_force_rethow(_rethrow);";
1892}
1893
Fariborz Jahanian11671902012-02-07 17:11:38 +00001894/// RewriteObjCSynchronizedStmt -
1895/// This routine rewrites @synchronized(expr) stmt;
1896/// into:
1897/// objc_sync_enter(expr);
1898/// @try stmt @finally { objc_sync_exit(expr); }
1899///
1900Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1901 // Get the start location and compute the semi location.
1902 SourceLocation startLoc = S->getLocStart();
1903 const char *startBuf = SM->getCharacterData(startLoc);
1904
1905 assert((*startBuf == '@') && "bogus @synchronized location");
1906
1907 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001908 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1909 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001910 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001911
Fariborz Jahanian11671902012-02-07 17:11:38 +00001912 const char *lparenBuf = startBuf;
1913 while (*lparenBuf != '(') lparenBuf++;
1914 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001915
1916 buf = "; objc_sync_enter(_sync_obj);\n";
1917 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1918 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1919 buf += "\n\tid sync_exit;";
1920 buf += "\n\t} _sync_exit(_sync_obj);\n";
1921
1922 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1923 // the sync expression is typically a message expression that's already
1924 // been rewritten! (which implies the SourceLocation's are invalid).
1925 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1926 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1927 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1928 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1929
1930 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1931 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1932 assert (*LBraceLocBuf == '{');
1933 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001934
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001935 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001936 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1937 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001938
1939 buf = "} catch (id e) {_rethrow = e;}\n";
1940 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001941 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001942 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001943
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001944 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001945
Fariborz Jahanian11671902012-02-07 17:11:38 +00001946 return 0;
1947}
1948
1949void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1950{
1951 // Perform a bottom up traversal of all children.
1952 for (Stmt::child_range CI = S->children(); CI; ++CI)
1953 if (*CI)
1954 WarnAboutReturnGotoStmts(*CI);
1955
1956 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1957 Diags.Report(Context->getFullLoc(S->getLocStart()),
1958 TryFinallyContainsReturnDiag);
1959 }
1960 return;
1961}
1962
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001963Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1964 SourceLocation startLoc = S->getAtLoc();
1965 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001966 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1967 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001968
1969 return 0;
1970}
1971
Fariborz Jahanian11671902012-02-07 17:11:38 +00001972Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001973 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001974 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001975 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001976 SourceLocation TryLocation = S->getAtTryLoc();
1977 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001978
1979 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001980 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001981 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001982 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001983 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001984 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001985 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001986 // Get the start location and compute the semi location.
1987 SourceLocation startLoc = S->getLocStart();
1988 const char *startBuf = SM->getCharacterData(startLoc);
1989
1990 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001991 if (finalStmt)
1992 ReplaceText(startLoc, 1, buf);
1993 else
1994 // @try -> try
1995 ReplaceText(startLoc, 1, "");
1996
Fariborz Jahanian11671902012-02-07 17:11:38 +00001997 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1998 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001999 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002000
Fariborz Jahanian11671902012-02-07 17:11:38 +00002001 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002002 bool AtRemoved = false;
2003 if (catchDecl) {
2004 QualType t = catchDecl->getType();
2005 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2006 // Should be a pointer to a class.
2007 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2008 if (IDecl) {
2009 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002010 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2011
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002012 startBuf = SM->getCharacterData(startLoc);
2013 assert((*startBuf == '@') && "bogus @catch location");
2014 SourceLocation rParenLoc = Catch->getRParenLoc();
2015 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2016
2017 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002018 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002019 Result += " *_"; Result += catchDecl->getNameAsString();
2020 Result += ")";
2021 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2022 // Foo *e = (Foo *)_e;
2023 Result.clear();
2024 Result = "{ ";
2025 Result += IDecl->getNameAsString();
2026 Result += " *"; Result += catchDecl->getNameAsString();
2027 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2028 Result += "_"; Result += catchDecl->getNameAsString();
2029
2030 Result += "; ";
2031 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2032 ReplaceText(lBraceLoc, 1, Result);
2033 AtRemoved = true;
2034 }
2035 }
2036 }
2037 if (!AtRemoved)
2038 // @catch -> catch
2039 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002040
Fariborz Jahanian11671902012-02-07 17:11:38 +00002041 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002042 if (finalStmt) {
2043 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002044 SourceLocation FinallyLoc = finalStmt->getLocStart();
2045
2046 if (noCatch) {
2047 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2048 buf += "catch (id e) {_rethrow = e;}\n";
2049 }
2050 else {
2051 buf += "}\n";
2052 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2053 buf += "catch (id e) {_rethrow = e;}\n";
2054 }
2055
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002056 SourceLocation startFinalLoc = finalStmt->getLocStart();
2057 ReplaceText(startFinalLoc, 8, buf);
2058 Stmt *body = finalStmt->getFinallyBody();
2059 SourceLocation startFinalBodyLoc = body->getLocStart();
2060 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002061 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002062 ReplaceText(startFinalBodyLoc, 1, buf);
2063
2064 SourceLocation endFinalBodyLoc = body->getLocEnd();
2065 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002066 // Now check for any return/continue/go statements within the @try.
2067 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002068 }
2069
Fariborz Jahanian11671902012-02-07 17:11:38 +00002070 return 0;
2071}
2072
2073// This can't be done with ReplaceStmt(S, ThrowExpr), since
2074// the throw expression is typically a message expression that's already
2075// been rewritten! (which implies the SourceLocation's are invalid).
2076Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2077 // Get the start location and compute the semi location.
2078 SourceLocation startLoc = S->getLocStart();
2079 const char *startBuf = SM->getCharacterData(startLoc);
2080
2081 assert((*startBuf == '@') && "bogus @throw location");
2082
2083 std::string buf;
2084 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2085 if (S->getThrowExpr())
2086 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002087 else
2088 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002089
2090 // handle "@ throw" correctly.
2091 const char *wBuf = strchr(startBuf, 'w');
2092 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2093 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2094
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002095 SourceLocation endLoc = S->getLocEnd();
2096 const char *endBuf = SM->getCharacterData(endLoc);
2097 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002098 assert((*semiBuf == ';') && "@throw: can't find ';'");
2099 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002100 if (S->getThrowExpr())
2101 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002102 return 0;
2103}
2104
2105Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2106 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002107 std::string StrEncoding;
2108 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002109 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002110 ReplaceStmt(Exp, Replacement);
2111
2112 // Replace this subexpr in the parent.
2113 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2114 return Replacement;
2115}
2116
2117Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2118 if (!SelGetUidFunctionDecl)
2119 SynthSelGetUidFunctionDecl();
2120 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2121 // Create a call to sel_registerName("selName").
2122 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002123 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002124 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2125 &SelExprs[0], SelExprs.size());
2126 ReplaceStmt(Exp, SelExp);
2127 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2128 return SelExp;
2129}
2130
2131CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2132 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2133 SourceLocation EndLoc) {
2134 // Get the type, we will need to reference it in a couple spots.
2135 QualType msgSendType = FD->getType();
2136
2137 // Create a reference to the objc_msgSend() declaration.
2138 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002139 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002140
2141 // Now, we cast the reference to a pointer to the objc_msgSend type.
2142 QualType pToFunc = Context->getPointerType(msgSendType);
2143 ImplicitCastExpr *ICE =
2144 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2145 DRE, 0, VK_RValue);
2146
2147 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2148
2149 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002150 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002151 FT->getCallResultType(*Context),
2152 VK_RValue, EndLoc);
2153 return Exp;
2154}
2155
2156static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2157 const char *&startRef, const char *&endRef) {
2158 while (startBuf < endBuf) {
2159 if (*startBuf == '<')
2160 startRef = startBuf; // mark the start.
2161 if (*startBuf == '>') {
2162 if (startRef && *startRef == '<') {
2163 endRef = startBuf; // mark the end.
2164 return true;
2165 }
2166 return false;
2167 }
2168 startBuf++;
2169 }
2170 return false;
2171}
2172
2173static void scanToNextArgument(const char *&argRef) {
2174 int angle = 0;
2175 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2176 if (*argRef == '<')
2177 angle++;
2178 else if (*argRef == '>')
2179 angle--;
2180 argRef++;
2181 }
2182 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2183}
2184
2185bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2186 if (T->isObjCQualifiedIdType())
2187 return true;
2188 if (const PointerType *PT = T->getAs<PointerType>()) {
2189 if (PT->getPointeeType()->isObjCQualifiedIdType())
2190 return true;
2191 }
2192 if (T->isObjCObjectPointerType()) {
2193 T = T->getPointeeType();
2194 return T->isObjCQualifiedInterfaceType();
2195 }
2196 if (T->isArrayType()) {
2197 QualType ElemTy = Context->getBaseElementType(T);
2198 return needToScanForQualifiers(ElemTy);
2199 }
2200 return false;
2201}
2202
2203void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2204 QualType Type = E->getType();
2205 if (needToScanForQualifiers(Type)) {
2206 SourceLocation Loc, EndLoc;
2207
2208 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2209 Loc = ECE->getLParenLoc();
2210 EndLoc = ECE->getRParenLoc();
2211 } else {
2212 Loc = E->getLocStart();
2213 EndLoc = E->getLocEnd();
2214 }
2215 // This will defend against trying to rewrite synthesized expressions.
2216 if (Loc.isInvalid() || EndLoc.isInvalid())
2217 return;
2218
2219 const char *startBuf = SM->getCharacterData(Loc);
2220 const char *endBuf = SM->getCharacterData(EndLoc);
2221 const char *startRef = 0, *endRef = 0;
2222 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2223 // Get the locations of the startRef, endRef.
2224 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2225 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2226 // Comment out the protocol references.
2227 InsertText(LessLoc, "/*");
2228 InsertText(GreaterLoc, "*/");
2229 }
2230 }
2231}
2232
2233void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2234 SourceLocation Loc;
2235 QualType Type;
2236 const FunctionProtoType *proto = 0;
2237 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2238 Loc = VD->getLocation();
2239 Type = VD->getType();
2240 }
2241 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2242 Loc = FD->getLocation();
2243 // Check for ObjC 'id' and class types that have been adorned with protocol
2244 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2245 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2246 assert(funcType && "missing function type");
2247 proto = dyn_cast<FunctionProtoType>(funcType);
2248 if (!proto)
2249 return;
Alp Toker314cc812014-01-25 16:55:45 +00002250 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002251 }
2252 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2253 Loc = FD->getLocation();
2254 Type = FD->getType();
2255 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002256 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2257 Loc = TD->getLocation();
2258 Type = TD->getUnderlyingType();
2259 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002260 else
2261 return;
2262
2263 if (needToScanForQualifiers(Type)) {
2264 // Since types are unique, we need to scan the buffer.
2265
2266 const char *endBuf = SM->getCharacterData(Loc);
2267 const char *startBuf = endBuf;
2268 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2269 startBuf--; // scan backward (from the decl location) for return type.
2270 const char *startRef = 0, *endRef = 0;
2271 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2272 // Get the locations of the startRef, endRef.
2273 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2274 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2275 // Comment out the protocol references.
2276 InsertText(LessLoc, "/*");
2277 InsertText(GreaterLoc, "*/");
2278 }
2279 }
2280 if (!proto)
2281 return; // most likely, was a variable
2282 // Now check arguments.
2283 const char *startBuf = SM->getCharacterData(Loc);
2284 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002285 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2286 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002287 // Since types are unique, we need to scan the buffer.
2288
2289 const char *endBuf = startBuf;
2290 // scan forward (from the decl location) for argument types.
2291 scanToNextArgument(endBuf);
2292 const char *startRef = 0, *endRef = 0;
2293 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2294 // Get the locations of the startRef, endRef.
2295 SourceLocation LessLoc =
2296 Loc.getLocWithOffset(startRef-startFuncBuf);
2297 SourceLocation GreaterLoc =
2298 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2299 // Comment out the protocol references.
2300 InsertText(LessLoc, "/*");
2301 InsertText(GreaterLoc, "*/");
2302 }
2303 startBuf = ++endBuf;
2304 }
2305 else {
2306 // If the function name is derived from a macro expansion, then the
2307 // argument buffer will not follow the name. Need to speak with Chris.
2308 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2309 startBuf++; // scan forward (from the decl location) for argument types.
2310 startBuf++;
2311 }
2312 }
2313}
2314
2315void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2316 QualType QT = ND->getType();
2317 const Type* TypePtr = QT->getAs<Type>();
2318 if (!isa<TypeOfExprType>(TypePtr))
2319 return;
2320 while (isa<TypeOfExprType>(TypePtr)) {
2321 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2322 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2323 TypePtr = QT->getAs<Type>();
2324 }
2325 // FIXME. This will not work for multiple declarators; as in:
2326 // __typeof__(a) b,c,d;
2327 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2328 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2329 const char *startBuf = SM->getCharacterData(DeclLoc);
2330 if (ND->getInit()) {
2331 std::string Name(ND->getNameAsString());
2332 TypeAsString += " " + Name + " = ";
2333 Expr *E = ND->getInit();
2334 SourceLocation startLoc;
2335 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2336 startLoc = ECE->getLParenLoc();
2337 else
2338 startLoc = E->getLocStart();
2339 startLoc = SM->getExpansionLoc(startLoc);
2340 const char *endBuf = SM->getCharacterData(startLoc);
2341 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2342 }
2343 else {
2344 SourceLocation X = ND->getLocEnd();
2345 X = SM->getExpansionLoc(X);
2346 const char *endBuf = SM->getCharacterData(X);
2347 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2348 }
2349}
2350
2351// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2352void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2353 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2354 SmallVector<QualType, 16> ArgTys;
2355 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2356 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002357 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002358 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002359 SourceLocation(),
2360 SourceLocation(),
2361 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002362 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002363}
2364
2365void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2366 // declared in <objc/objc.h>
2367 if (FD->getIdentifier() &&
2368 FD->getName() == "sel_registerName") {
2369 SelGetUidFunctionDecl = FD;
2370 return;
2371 }
2372 RewriteObjCQualifiedInterfaceTypes(FD);
2373}
2374
2375void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2376 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2377 const char *argPtr = TypeString.c_str();
2378 if (!strchr(argPtr, '^')) {
2379 Str += TypeString;
2380 return;
2381 }
2382 while (*argPtr) {
2383 Str += (*argPtr == '^' ? '*' : *argPtr);
2384 argPtr++;
2385 }
2386}
2387
2388// FIXME. Consolidate this routine with RewriteBlockPointerType.
2389void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2390 ValueDecl *VD) {
2391 QualType Type = VD->getType();
2392 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2393 const char *argPtr = TypeString.c_str();
2394 int paren = 0;
2395 while (*argPtr) {
2396 switch (*argPtr) {
2397 case '(':
2398 Str += *argPtr;
2399 paren++;
2400 break;
2401 case ')':
2402 Str += *argPtr;
2403 paren--;
2404 break;
2405 case '^':
2406 Str += '*';
2407 if (paren == 1)
2408 Str += VD->getNameAsString();
2409 break;
2410 default:
2411 Str += *argPtr;
2412 break;
2413 }
2414 argPtr++;
2415 }
2416}
2417
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002418void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2419 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2420 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2421 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2422 if (!proto)
2423 return;
Alp Toker314cc812014-01-25 16:55:45 +00002424 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002425 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2426 FdStr += " ";
2427 FdStr += FD->getName();
2428 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002429 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002430 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002431 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002432 RewriteBlockPointerType(FdStr, ArgType);
2433 if (i+1 < numArgs)
2434 FdStr += ", ";
2435 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002436 if (FD->isVariadic()) {
2437 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2438 }
2439 else
2440 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002441 InsertText(FunLocStart, FdStr);
2442}
2443
Benjamin Kramer60509af2013-09-09 14:48:42 +00002444// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2445void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2446 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002447 return;
2448 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2449 SmallVector<QualType, 16> ArgTys;
2450 QualType argT = Context->getObjCIdType();
2451 assert(!argT.isNull() && "Can't find 'id' type");
2452 ArgTys.push_back(argT);
2453 ArgTys.push_back(argT);
2454 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002455 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002456 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002457 SourceLocation(),
2458 SourceLocation(),
2459 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002460 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002461}
2462
2463// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2464void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2465 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2466 SmallVector<QualType, 16> ArgTys;
2467 QualType argT = Context->getObjCIdType();
2468 assert(!argT.isNull() && "Can't find 'id' type");
2469 ArgTys.push_back(argT);
2470 argT = Context->getObjCSelType();
2471 assert(!argT.isNull() && "Can't find 'SEL' type");
2472 ArgTys.push_back(argT);
2473 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002474 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002475 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002476 SourceLocation(),
2477 SourceLocation(),
2478 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002479 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002480}
2481
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002482// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002483void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2484 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002485 SmallVector<QualType, 2> ArgTys;
2486 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002487 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002488 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002489 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002490 SourceLocation(),
2491 SourceLocation(),
2492 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002493 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002494}
2495
2496// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2497void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2498 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2499 SmallVector<QualType, 16> ArgTys;
2500 QualType argT = Context->getObjCIdType();
2501 assert(!argT.isNull() && "Can't find 'id' type");
2502 ArgTys.push_back(argT);
2503 argT = Context->getObjCSelType();
2504 assert(!argT.isNull() && "Can't find 'SEL' type");
2505 ArgTys.push_back(argT);
2506 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002507 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002508 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002509 SourceLocation(),
2510 SourceLocation(),
2511 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002512 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002513}
2514
2515// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002516// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002517void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2518 IdentifierInfo *msgSendIdent =
2519 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002520 SmallVector<QualType, 2> ArgTys;
2521 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002522 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002523 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002524 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2525 SourceLocation(),
2526 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002527 msgSendIdent,
2528 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002529 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002530}
2531
2532// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2533void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2534 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2535 SmallVector<QualType, 16> ArgTys;
2536 QualType argT = Context->getObjCIdType();
2537 assert(!argT.isNull() && "Can't find 'id' type");
2538 ArgTys.push_back(argT);
2539 argT = Context->getObjCSelType();
2540 assert(!argT.isNull() && "Can't find 'SEL' type");
2541 ArgTys.push_back(argT);
2542 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002543 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002544 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002545 SourceLocation(),
2546 SourceLocation(),
2547 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002548 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002549}
2550
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002551// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002552void RewriteModernObjC::SynthGetClassFunctionDecl() {
2553 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2554 SmallVector<QualType, 16> ArgTys;
2555 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002556 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002557 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002558 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002559 SourceLocation(),
2560 SourceLocation(),
2561 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002562 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002563}
2564
2565// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2566void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2567 IdentifierInfo *getSuperClassIdent =
2568 &Context->Idents.get("class_getSuperclass");
2569 SmallVector<QualType, 16> ArgTys;
2570 ArgTys.push_back(Context->getObjCClassType());
2571 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002572 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002573 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2574 SourceLocation(),
2575 SourceLocation(),
2576 getSuperClassIdent,
2577 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002578 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002579}
2580
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002581// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002582void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2583 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2584 SmallVector<QualType, 16> ArgTys;
2585 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002586 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002587 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002588 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002589 SourceLocation(),
2590 SourceLocation(),
2591 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002592 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002593}
2594
2595Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2596 QualType strType = getConstantStringStructType();
2597
2598 std::string S = "__NSConstantStringImpl_";
2599
2600 std::string tmpName = InFileName;
2601 unsigned i;
2602 for (i=0; i < tmpName.length(); i++) {
2603 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002604 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002605 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002606 tmpName[i] = '_';
2607 }
2608 S += tmpName;
2609 S += "_";
2610 S += utostr(NumObjCStringLiterals++);
2611
2612 Preamble += "static __NSConstantStringImpl " + S;
2613 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2614 Preamble += "0x000007c8,"; // utf8_str
2615 // The pretty printer for StringLiteral handles escape characters properly.
2616 std::string prettyBufS;
2617 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002618 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002619 Preamble += prettyBuf.str();
2620 Preamble += ",";
2621 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2622
2623 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2624 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002625 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002626 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002627 SourceLocation());
2628 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2629 Context->getPointerType(DRE->getType()),
2630 VK_RValue, OK_Ordinary,
2631 SourceLocation());
2632 // cast to NSConstantString *
2633 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2634 CK_CPointerToObjCPointerCast, Unop);
2635 ReplaceStmt(Exp, cast);
2636 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2637 return cast;
2638}
2639
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002640Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2641 unsigned IntSize =
2642 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2643
2644 Expr *FlagExp = IntegerLiteral::Create(*Context,
2645 llvm::APInt(IntSize, Exp->getValue()),
2646 Context->IntTy, Exp->getLocation());
2647 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2648 CK_BitCast, FlagExp);
2649 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2650 cast);
2651 ReplaceStmt(Exp, PE);
2652 return PE;
2653}
2654
Patrick Beard0caa3942012-04-19 00:25:12 +00002655Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002656 // synthesize declaration of helper functions needed in this routine.
2657 if (!SelGetUidFunctionDecl)
2658 SynthSelGetUidFunctionDecl();
2659 // use objc_msgSend() for all.
2660 if (!MsgSendFunctionDecl)
2661 SynthMsgSendFunctionDecl();
2662 if (!GetClassFunctionDecl)
2663 SynthGetClassFunctionDecl();
2664
2665 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2666 SourceLocation StartLoc = Exp->getLocStart();
2667 SourceLocation EndLoc = Exp->getLocEnd();
2668
2669 // Synthesize a call to objc_msgSend().
2670 SmallVector<Expr*, 4> MsgExprs;
2671 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002672
Patrick Beard0caa3942012-04-19 00:25:12 +00002673 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2674 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2675 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002676
Patrick Beard0caa3942012-04-19 00:25:12 +00002677 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002678 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002679 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2680 &ClsExprs[0],
2681 ClsExprs.size(),
2682 StartLoc, EndLoc);
2683 MsgExprs.push_back(Cls);
2684
Patrick Beard0caa3942012-04-19 00:25:12 +00002685 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002686 // it will be the 2nd argument.
2687 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002688 SelExprs.push_back(
2689 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002690 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2691 &SelExprs[0], SelExprs.size(),
2692 StartLoc, EndLoc);
2693 MsgExprs.push_back(SelExp);
2694
Patrick Beard0caa3942012-04-19 00:25:12 +00002695 // User provided sub-expression is the 3rd, and last, argument.
2696 Expr *subExpr = Exp->getSubExpr();
2697 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002698 QualType type = ICE->getType();
2699 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2700 CastKind CK = CK_BitCast;
2701 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2702 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002703 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002704 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002705 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002706
2707 SmallVector<QualType, 4> ArgTypes;
2708 ArgTypes.push_back(Context->getObjCIdType());
2709 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002710 for (const auto PI : BoxingMethod->parameters())
2711 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002712
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002713 QualType returnType = Exp->getType();
2714 // Get the type, we will need to reference it in a couple spots.
2715 QualType msgSendType = MsgSendFlavor->getType();
2716
2717 // Create a reference to the objc_msgSend() declaration.
2718 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2719 VK_LValue, SourceLocation());
2720
2721 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002722 Context->getPointerType(Context->VoidTy),
2723 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002724
2725 // Now do the "normal" pointer to function cast.
2726 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002727 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002728 castType = Context->getPointerType(castType);
2729 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2730 cast);
2731
2732 // Don't forget the parens to enforce the proper binding.
2733 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2734
2735 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002736 CallExpr *CE = new (Context)
2737 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002738 ReplaceStmt(Exp, CE);
2739 return CE;
2740}
2741
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002742Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2743 // synthesize declaration of helper functions needed in this routine.
2744 if (!SelGetUidFunctionDecl)
2745 SynthSelGetUidFunctionDecl();
2746 // use objc_msgSend() for all.
2747 if (!MsgSendFunctionDecl)
2748 SynthMsgSendFunctionDecl();
2749 if (!GetClassFunctionDecl)
2750 SynthGetClassFunctionDecl();
2751
2752 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2753 SourceLocation StartLoc = Exp->getLocStart();
2754 SourceLocation EndLoc = Exp->getLocEnd();
2755
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002756 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002757 QualType IntQT = Context->IntTy;
2758 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002759 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002760 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002761 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2762 DeclRefExpr *NSArrayDRE =
2763 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2764 SourceLocation());
2765
2766 SmallVector<Expr*, 16> InitExprs;
2767 unsigned NumElements = Exp->getNumElements();
2768 unsigned UnsignedIntSize =
2769 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2770 Expr *count = IntegerLiteral::Create(*Context,
2771 llvm::APInt(UnsignedIntSize, NumElements),
2772 Context->UnsignedIntTy, SourceLocation());
2773 InitExprs.push_back(count);
2774 for (unsigned i = 0; i < NumElements; i++)
2775 InitExprs.push_back(Exp->getElement(i));
2776 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002777 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002778 NSArrayFType, VK_LValue, SourceLocation());
2779
2780 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2781 SourceLocation(),
2782 &Context->Idents.get("arr"),
2783 Context->getPointerType(Context->VoidPtrTy), 0,
2784 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002785 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002786 MemberExpr *ArrayLiteralME =
2787 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2788 SourceLocation(),
2789 ARRFD->getType(), VK_LValue,
2790 OK_Ordinary);
2791 QualType ConstIdT = Context->getObjCIdType().withConst();
2792 CStyleCastExpr * ArrayLiteralObjects =
2793 NoTypeInfoCStyleCastExpr(Context,
2794 Context->getPointerType(ConstIdT),
2795 CK_BitCast,
2796 ArrayLiteralME);
2797
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002798 // Synthesize a call to objc_msgSend().
2799 SmallVector<Expr*, 32> MsgExprs;
2800 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002801 QualType expType = Exp->getType();
2802
2803 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2804 ObjCInterfaceDecl *Class =
2805 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2806
2807 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002808 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002809 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2810 &ClsExprs[0],
2811 ClsExprs.size(),
2812 StartLoc, EndLoc);
2813 MsgExprs.push_back(Cls);
2814
2815 // Create a call to sel_registerName("arrayWithObjects:count:").
2816 // it will be the 2nd argument.
2817 SmallVector<Expr*, 4> SelExprs;
2818 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002819 SelExprs.push_back(
2820 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002821 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2822 &SelExprs[0], SelExprs.size(),
2823 StartLoc, EndLoc);
2824 MsgExprs.push_back(SelExp);
2825
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002826 // (const id [])objects
2827 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002828
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002829 // (NSUInteger)cnt
2830 Expr *cnt = IntegerLiteral::Create(*Context,
2831 llvm::APInt(UnsignedIntSize, NumElements),
2832 Context->UnsignedIntTy, SourceLocation());
2833 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002834
2835
2836 SmallVector<QualType, 4> ArgTypes;
2837 ArgTypes.push_back(Context->getObjCIdType());
2838 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002839 for (const auto *PI : ArrayMethod->params())
2840 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002841
2842 QualType returnType = Exp->getType();
2843 // Get the type, we will need to reference it in a couple spots.
2844 QualType msgSendType = MsgSendFlavor->getType();
2845
2846 // Create a reference to the objc_msgSend() declaration.
2847 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2848 VK_LValue, SourceLocation());
2849
2850 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2851 Context->getPointerType(Context->VoidTy),
2852 CK_BitCast, DRE);
2853
2854 // Now do the "normal" pointer to function cast.
2855 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002856 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002857 castType = Context->getPointerType(castType);
2858 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2859 cast);
2860
2861 // Don't forget the parens to enforce the proper binding.
2862 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2863
2864 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002865 CallExpr *CE = new (Context)
2866 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002867 ReplaceStmt(Exp, CE);
2868 return CE;
2869}
2870
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002871Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2872 // synthesize declaration of helper functions needed in this routine.
2873 if (!SelGetUidFunctionDecl)
2874 SynthSelGetUidFunctionDecl();
2875 // use objc_msgSend() for all.
2876 if (!MsgSendFunctionDecl)
2877 SynthMsgSendFunctionDecl();
2878 if (!GetClassFunctionDecl)
2879 SynthGetClassFunctionDecl();
2880
2881 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2882 SourceLocation StartLoc = Exp->getLocStart();
2883 SourceLocation EndLoc = Exp->getLocEnd();
2884
2885 // Build the expression: __NSContainer_literal(int, ...).arr
2886 QualType IntQT = Context->IntTy;
2887 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002888 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002889 std::string NSDictFName("__NSContainer_literal");
2890 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2891 DeclRefExpr *NSDictDRE =
2892 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2893 SourceLocation());
2894
2895 SmallVector<Expr*, 16> KeyExprs;
2896 SmallVector<Expr*, 16> ValueExprs;
2897
2898 unsigned NumElements = Exp->getNumElements();
2899 unsigned UnsignedIntSize =
2900 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2901 Expr *count = IntegerLiteral::Create(*Context,
2902 llvm::APInt(UnsignedIntSize, NumElements),
2903 Context->UnsignedIntTy, SourceLocation());
2904 KeyExprs.push_back(count);
2905 ValueExprs.push_back(count);
2906 for (unsigned i = 0; i < NumElements; i++) {
2907 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2908 KeyExprs.push_back(Element.Key);
2909 ValueExprs.push_back(Element.Value);
2910 }
2911
2912 // (const id [])objects
2913 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002914 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002915 NSDictFType, VK_LValue, SourceLocation());
2916
2917 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2918 SourceLocation(),
2919 &Context->Idents.get("arr"),
2920 Context->getPointerType(Context->VoidPtrTy), 0,
2921 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002922 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002923 MemberExpr *DictLiteralValueME =
2924 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2925 SourceLocation(),
2926 ARRFD->getType(), VK_LValue,
2927 OK_Ordinary);
2928 QualType ConstIdT = Context->getObjCIdType().withConst();
2929 CStyleCastExpr * DictValueObjects =
2930 NoTypeInfoCStyleCastExpr(Context,
2931 Context->getPointerType(ConstIdT),
2932 CK_BitCast,
2933 DictLiteralValueME);
2934 // (const id <NSCopying> [])keys
2935 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002936 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002937 NSDictFType, VK_LValue, SourceLocation());
2938
2939 MemberExpr *DictLiteralKeyME =
2940 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2941 SourceLocation(),
2942 ARRFD->getType(), VK_LValue,
2943 OK_Ordinary);
2944
2945 CStyleCastExpr * DictKeyObjects =
2946 NoTypeInfoCStyleCastExpr(Context,
2947 Context->getPointerType(ConstIdT),
2948 CK_BitCast,
2949 DictLiteralKeyME);
2950
2951
2952
2953 // Synthesize a call to objc_msgSend().
2954 SmallVector<Expr*, 32> MsgExprs;
2955 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002956 QualType expType = Exp->getType();
2957
2958 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2959 ObjCInterfaceDecl *Class =
2960 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2961
2962 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002963 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002964 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2965 &ClsExprs[0],
2966 ClsExprs.size(),
2967 StartLoc, EndLoc);
2968 MsgExprs.push_back(Cls);
2969
2970 // Create a call to sel_registerName("arrayWithObjects:count:").
2971 // it will be the 2nd argument.
2972 SmallVector<Expr*, 4> SelExprs;
2973 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002974 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002975 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2976 &SelExprs[0], SelExprs.size(),
2977 StartLoc, EndLoc);
2978 MsgExprs.push_back(SelExp);
2979
2980 // (const id [])objects
2981 MsgExprs.push_back(DictValueObjects);
2982
2983 // (const id <NSCopying> [])keys
2984 MsgExprs.push_back(DictKeyObjects);
2985
2986 // (NSUInteger)cnt
2987 Expr *cnt = IntegerLiteral::Create(*Context,
2988 llvm::APInt(UnsignedIntSize, NumElements),
2989 Context->UnsignedIntTy, SourceLocation());
2990 MsgExprs.push_back(cnt);
2991
2992
2993 SmallVector<QualType, 8> ArgTypes;
2994 ArgTypes.push_back(Context->getObjCIdType());
2995 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002996 for (const auto *PI : DictMethod->params()) {
2997 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002998 if (const PointerType* PT = T->getAs<PointerType>()) {
2999 QualType PointeeTy = PT->getPointeeType();
3000 convertToUnqualifiedObjCType(PointeeTy);
3001 T = Context->getPointerType(PointeeTy);
3002 }
3003 ArgTypes.push_back(T);
3004 }
3005
3006 QualType returnType = Exp->getType();
3007 // Get the type, we will need to reference it in a couple spots.
3008 QualType msgSendType = MsgSendFlavor->getType();
3009
3010 // Create a reference to the objc_msgSend() declaration.
3011 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3012 VK_LValue, SourceLocation());
3013
3014 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3015 Context->getPointerType(Context->VoidTy),
3016 CK_BitCast, DRE);
3017
3018 // Now do the "normal" pointer to function cast.
3019 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003020 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003021 castType = Context->getPointerType(castType);
3022 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3023 cast);
3024
3025 // Don't forget the parens to enforce the proper binding.
3026 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3027
3028 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003029 CallExpr *CE = new (Context)
3030 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003031 ReplaceStmt(Exp, CE);
3032 return CE;
3033}
3034
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003035// struct __rw_objc_super {
3036// struct objc_object *object; struct objc_object *superClass;
3037// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003038QualType RewriteModernObjC::getSuperStructType() {
3039 if (!SuperStructDecl) {
3040 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3041 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003042 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003043 QualType FieldTypes[2];
3044
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003045 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003046 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003047 // struct objc_object *superClass;
3048 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003049
3050 // Create fields
3051 for (unsigned i = 0; i < 2; ++i) {
3052 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3053 SourceLocation(),
3054 SourceLocation(), 0,
3055 FieldTypes[i], 0,
3056 /*BitWidth=*/0,
3057 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003058 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003059 }
3060
3061 SuperStructDecl->completeDefinition();
3062 }
3063 return Context->getTagDeclType(SuperStructDecl);
3064}
3065
3066QualType RewriteModernObjC::getConstantStringStructType() {
3067 if (!ConstantStringDecl) {
3068 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3069 SourceLocation(), SourceLocation(),
3070 &Context->Idents.get("__NSConstantStringImpl"));
3071 QualType FieldTypes[4];
3072
3073 // struct objc_object *receiver;
3074 FieldTypes[0] = Context->getObjCIdType();
3075 // int flags;
3076 FieldTypes[1] = Context->IntTy;
3077 // char *str;
3078 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3079 // long length;
3080 FieldTypes[3] = Context->LongTy;
3081
3082 // Create fields
3083 for (unsigned i = 0; i < 4; ++i) {
3084 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3085 ConstantStringDecl,
3086 SourceLocation(),
3087 SourceLocation(), 0,
3088 FieldTypes[i], 0,
3089 /*BitWidth=*/0,
3090 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003091 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003092 }
3093
3094 ConstantStringDecl->completeDefinition();
3095 }
3096 return Context->getTagDeclType(ConstantStringDecl);
3097}
3098
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003099/// getFunctionSourceLocation - returns start location of a function
3100/// definition. Complication arises when function has declared as
3101/// extern "C" or extern "C" {...}
3102static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3103 FunctionDecl *FD) {
3104 if (FD->isExternC() && !FD->isMain()) {
3105 const DeclContext *DC = FD->getDeclContext();
3106 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3107 // if it is extern "C" {...}, return function decl's own location.
3108 if (!LSD->getRBraceLoc().isValid())
3109 return LSD->getExternLoc();
3110 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003111 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003112 R.RewriteBlockLiteralFunctionDecl(FD);
3113 return FD->getTypeSpecStartLoc();
3114}
3115
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003116void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3117
3118 SourceLocation Location = D->getLocation();
3119
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003120 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003121 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003122 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3123 LineString += utostr(PLoc.getLine());
3124 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003125 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003126 if (isa<ObjCMethodDecl>(D))
3127 LineString += "\"";
3128 else LineString += "\"\n";
3129
3130 Location = D->getLocStart();
3131 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3132 if (FD->isExternC() && !FD->isMain()) {
3133 const DeclContext *DC = FD->getDeclContext();
3134 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3135 // if it is extern "C" {...}, return function decl's own location.
3136 if (!LSD->getRBraceLoc().isValid())
3137 Location = LSD->getExternLoc();
3138 }
3139 }
3140 InsertText(Location, LineString);
3141 }
3142}
3143
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003144/// SynthMsgSendStretCallExpr - This routine translates message expression
3145/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3146/// nil check on receiver must be performed before calling objc_msgSend_stret.
3147/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3148/// msgSendType - function type of objc_msgSend_stret(...)
3149/// returnType - Result type of the method being synthesized.
3150/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3151/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3152/// starting with receiver.
3153/// Method - Method being rewritten.
3154Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003155 QualType returnType,
3156 SmallVectorImpl<QualType> &ArgTypes,
3157 SmallVectorImpl<Expr*> &MsgExprs,
3158 ObjCMethodDecl *Method) {
3159 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003160 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3161 Method ? Method->isVariadic()
3162 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003163 castType = Context->getPointerType(castType);
3164
3165 // build type for containing the objc_msgSend_stret object.
3166 static unsigned stretCount=0;
3167 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003168 std::string str =
3169 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003170 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003171 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003172 str += " {\n\t";
3173 str += name;
3174 str += "(id receiver, SEL sel";
3175 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003176 std::string ArgName = "arg"; ArgName += utostr(i);
3177 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3178 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003179 }
3180 // could be vararg.
3181 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003182 std::string ArgName = "arg"; ArgName += utostr(i);
3183 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3184 Context->getPrintingPolicy());
3185 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003186 }
3187
3188 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003189 str += "\t unsigned size = sizeof(";
3190 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3191
3192 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3193
3194 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3195 str += ")(void *)objc_msgSend)(receiver, sel";
3196 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3197 str += ", arg"; str += utostr(i);
3198 }
3199 // could be vararg.
3200 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3201 str += ", arg"; str += utostr(i);
3202 }
3203 str+= ");\n";
3204
3205 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003206 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3207 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003208
3209
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003210 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3211 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3212 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3213 str += ", arg"; str += utostr(i);
3214 }
3215 // could be vararg.
3216 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3217 str += ", arg"; str += utostr(i);
3218 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003219 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003220
3221
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003222 str += "\t}\n";
3223 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3224 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003225 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003226 SourceLocation FunLocStart;
3227 if (CurFunctionDef)
3228 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3229 else {
3230 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3231 FunLocStart = CurMethodDef->getLocStart();
3232 }
3233
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003234 InsertText(FunLocStart, str);
3235 ++stretCount;
3236
3237 // AST for __Stretn(receiver, args).s;
3238 IdentifierInfo *ID = &Context->Idents.get(name);
3239 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003240 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003241 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003242 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3243 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003244 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003245 castType, VK_LValue, SourceLocation());
3246
3247 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3248 SourceLocation(),
3249 &Context->Idents.get("s"),
3250 returnType, 0,
3251 /*BitWidth=*/0, /*Mutable=*/true,
3252 ICIS_NoInit);
3253 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3254 FieldD->getType(), VK_LValue,
3255 OK_Ordinary);
3256
3257 return ME;
3258}
3259
Fariborz Jahanian11671902012-02-07 17:11:38 +00003260Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3261 SourceLocation StartLoc,
3262 SourceLocation EndLoc) {
3263 if (!SelGetUidFunctionDecl)
3264 SynthSelGetUidFunctionDecl();
3265 if (!MsgSendFunctionDecl)
3266 SynthMsgSendFunctionDecl();
3267 if (!MsgSendSuperFunctionDecl)
3268 SynthMsgSendSuperFunctionDecl();
3269 if (!MsgSendStretFunctionDecl)
3270 SynthMsgSendStretFunctionDecl();
3271 if (!MsgSendSuperStretFunctionDecl)
3272 SynthMsgSendSuperStretFunctionDecl();
3273 if (!MsgSendFpretFunctionDecl)
3274 SynthMsgSendFpretFunctionDecl();
3275 if (!GetClassFunctionDecl)
3276 SynthGetClassFunctionDecl();
3277 if (!GetSuperClassFunctionDecl)
3278 SynthGetSuperClassFunctionDecl();
3279 if (!GetMetaClassFunctionDecl)
3280 SynthGetMetaClassFunctionDecl();
3281
3282 // default to objc_msgSend().
3283 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3284 // May need to use objc_msgSend_stret() as well.
3285 FunctionDecl *MsgSendStretFlavor = 0;
3286 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003287 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003288 if (resultType->isRecordType())
3289 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3290 else if (resultType->isRealFloatingType())
3291 MsgSendFlavor = MsgSendFpretFunctionDecl;
3292 }
3293
3294 // Synthesize a call to objc_msgSend().
3295 SmallVector<Expr*, 8> MsgExprs;
3296 switch (Exp->getReceiverKind()) {
3297 case ObjCMessageExpr::SuperClass: {
3298 MsgSendFlavor = MsgSendSuperFunctionDecl;
3299 if (MsgSendStretFlavor)
3300 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3301 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3302
3303 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3304
3305 SmallVector<Expr*, 4> InitExprs;
3306
3307 // set the receiver to self, the first argument to all methods.
3308 InitExprs.push_back(
3309 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3310 CK_BitCast,
3311 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003312 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003313 Context->getObjCIdType(),
3314 VK_RValue,
3315 SourceLocation()))
3316 ); // set the 'receiver'.
3317
3318 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3319 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003320 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003321 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003322 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3323 &ClsExprs[0],
3324 ClsExprs.size(),
3325 StartLoc,
3326 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003327 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003328 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003329 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3330 &ClsExprs[0], ClsExprs.size(),
3331 StartLoc, EndLoc);
3332
3333 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3334 // To turn off a warning, type-cast to 'id'
3335 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3336 NoTypeInfoCStyleCastExpr(Context,
3337 Context->getObjCIdType(),
3338 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003339 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003340 QualType superType = getSuperStructType();
3341 Expr *SuperRep;
3342
3343 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003344 SynthSuperConstructorFunctionDecl();
3345 // Simulate a constructor call...
3346 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003347 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003348 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003349 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003350 superType, VK_LValue,
3351 SourceLocation());
3352 // The code for super is a little tricky to prevent collision with
3353 // the structure definition in the header. The rewriter has it's own
3354 // internal definition (__rw_objc_super) that is uses. This is why
3355 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003356 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003357 //
3358 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3359 Context->getPointerType(SuperRep->getType()),
3360 VK_RValue, OK_Ordinary,
3361 SourceLocation());
3362 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3363 Context->getPointerType(superType),
3364 CK_BitCast, SuperRep);
3365 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003366 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003367 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003368 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003369 SourceLocation());
3370 TypeSourceInfo *superTInfo
3371 = Context->getTrivialTypeSourceInfo(superType);
3372 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3373 superType, VK_LValue,
3374 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003375 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003376 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3377 Context->getPointerType(SuperRep->getType()),
3378 VK_RValue, OK_Ordinary,
3379 SourceLocation());
3380 }
3381 MsgExprs.push_back(SuperRep);
3382 break;
3383 }
3384
3385 case ObjCMessageExpr::Class: {
3386 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003387 ObjCInterfaceDecl *Class
3388 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3389 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003390 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003391 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3392 &ClsExprs[0],
3393 ClsExprs.size(),
3394 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003395 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3396 Context->getObjCIdType(),
3397 CK_BitCast, Cls);
3398 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003399 break;
3400 }
3401
3402 case ObjCMessageExpr::SuperInstance:{
3403 MsgSendFlavor = MsgSendSuperFunctionDecl;
3404 if (MsgSendStretFlavor)
3405 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3406 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3407 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3408 SmallVector<Expr*, 4> InitExprs;
3409
3410 InitExprs.push_back(
3411 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3412 CK_BitCast,
3413 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003414 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003415 Context->getObjCIdType(),
3416 VK_RValue, SourceLocation()))
3417 ); // set the 'receiver'.
3418
3419 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3420 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003421 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003422 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003423 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3424 &ClsExprs[0],
3425 ClsExprs.size(),
3426 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003427 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003428 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003429 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3430 &ClsExprs[0], ClsExprs.size(),
3431 StartLoc, EndLoc);
3432
3433 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3434 // To turn off a warning, type-cast to 'id'
3435 InitExprs.push_back(
3436 // set 'super class', using class_getSuperclass().
3437 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3438 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003439 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003440 QualType superType = getSuperStructType();
3441 Expr *SuperRep;
3442
3443 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003444 SynthSuperConstructorFunctionDecl();
3445 // Simulate a constructor call...
3446 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003447 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003448 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003449 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003450 superType, VK_LValue, SourceLocation());
3451 // The code for super is a little tricky to prevent collision with
3452 // the structure definition in the header. The rewriter has it's own
3453 // internal definition (__rw_objc_super) that is uses. This is why
3454 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003455 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003456 //
3457 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3458 Context->getPointerType(SuperRep->getType()),
3459 VK_RValue, OK_Ordinary,
3460 SourceLocation());
3461 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3462 Context->getPointerType(superType),
3463 CK_BitCast, SuperRep);
3464 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003465 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003466 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003467 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003468 SourceLocation());
3469 TypeSourceInfo *superTInfo
3470 = Context->getTrivialTypeSourceInfo(superType);
3471 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3472 superType, VK_RValue, ILE,
3473 false);
3474 }
3475 MsgExprs.push_back(SuperRep);
3476 break;
3477 }
3478
3479 case ObjCMessageExpr::Instance: {
3480 // Remove all type-casts because it may contain objc-style types; e.g.
3481 // Foo<Proto> *.
3482 Expr *recExpr = Exp->getInstanceReceiver();
3483 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3484 recExpr = CE->getSubExpr();
3485 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3486 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3487 ? CK_BlockPointerToObjCPointerCast
3488 : CK_CPointerToObjCPointerCast;
3489
3490 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3491 CK, recExpr);
3492 MsgExprs.push_back(recExpr);
3493 break;
3494 }
3495 }
3496
3497 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3498 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003499 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003500 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3501 &SelExprs[0], SelExprs.size(),
3502 StartLoc,
3503 EndLoc);
3504 MsgExprs.push_back(SelExp);
3505
3506 // Now push any user supplied arguments.
3507 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3508 Expr *userExpr = Exp->getArg(i);
3509 // Make all implicit casts explicit...ICE comes in handy:-)
3510 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3511 // Reuse the ICE type, it is exactly what the doctor ordered.
3512 QualType type = ICE->getType();
3513 if (needToScanForQualifiers(type))
3514 type = Context->getObjCIdType();
3515 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3516 (void)convertBlockPointerToFunctionPointer(type);
3517 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3518 CastKind CK;
3519 if (SubExpr->getType()->isIntegralType(*Context) &&
3520 type->isBooleanType()) {
3521 CK = CK_IntegralToBoolean;
3522 } else if (type->isObjCObjectPointerType()) {
3523 if (SubExpr->getType()->isBlockPointerType()) {
3524 CK = CK_BlockPointerToObjCPointerCast;
3525 } else if (SubExpr->getType()->isPointerType()) {
3526 CK = CK_CPointerToObjCPointerCast;
3527 } else {
3528 CK = CK_BitCast;
3529 }
3530 } else {
3531 CK = CK_BitCast;
3532 }
3533
3534 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3535 }
3536 // Make id<P...> cast into an 'id' cast.
3537 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3538 if (CE->getType()->isObjCQualifiedIdType()) {
3539 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3540 userExpr = CE->getSubExpr();
3541 CastKind CK;
3542 if (userExpr->getType()->isIntegralType(*Context)) {
3543 CK = CK_IntegralToPointer;
3544 } else if (userExpr->getType()->isBlockPointerType()) {
3545 CK = CK_BlockPointerToObjCPointerCast;
3546 } else if (userExpr->getType()->isPointerType()) {
3547 CK = CK_CPointerToObjCPointerCast;
3548 } else {
3549 CK = CK_BitCast;
3550 }
3551 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3552 CK, userExpr);
3553 }
3554 }
3555 MsgExprs.push_back(userExpr);
3556 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3557 // out the argument in the original expression (since we aren't deleting
3558 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3559 //Exp->setArg(i, 0);
3560 }
3561 // Generate the funky cast.
3562 CastExpr *cast;
3563 SmallVector<QualType, 8> ArgTypes;
3564 QualType returnType;
3565
3566 // Push 'id' and 'SEL', the 2 implicit arguments.
3567 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3568 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3569 else
3570 ArgTypes.push_back(Context->getObjCIdType());
3571 ArgTypes.push_back(Context->getObjCSelType());
3572 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3573 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003574 for (const auto *PI : OMD->params()) {
3575 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003576 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003577 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003578 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3579 (void)convertBlockPointerToFunctionPointer(t);
3580 ArgTypes.push_back(t);
3581 }
3582 returnType = Exp->getType();
3583 convertToUnqualifiedObjCType(returnType);
3584 (void)convertBlockPointerToFunctionPointer(returnType);
3585 } else {
3586 returnType = Context->getObjCIdType();
3587 }
3588 // Get the type, we will need to reference it in a couple spots.
3589 QualType msgSendType = MsgSendFlavor->getType();
3590
3591 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003592 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003593 VK_LValue, SourceLocation());
3594
3595 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3596 // If we don't do this cast, we get the following bizarre warning/note:
3597 // xx.m:13: warning: function called through a non-compatible type
3598 // xx.m:13: note: if this code is reached, the program will abort
3599 cast = NoTypeInfoCStyleCastExpr(Context,
3600 Context->getPointerType(Context->VoidTy),
3601 CK_BitCast, DRE);
3602
3603 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003604 // If we don't have a method decl, force a variadic cast.
3605 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003606 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003607 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003608 castType = Context->getPointerType(castType);
3609 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3610 cast);
3611
3612 // Don't forget the parens to enforce the proper binding.
3613 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3614
3615 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003616 CallExpr *CE = new (Context)
3617 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003618 Stmt *ReplacingStmt = CE;
3619 if (MsgSendStretFlavor) {
3620 // We have the method which returns a struct/union. Must also generate
3621 // call to objc_msgSend_stret and hang both varieties on a conditional
3622 // expression which dictate which one to envoke depending on size of
3623 // method's return type.
3624
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003625 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3626 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003627 ArgTypes, MsgExprs,
3628 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003629 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003630 }
3631 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3632 return ReplacingStmt;
3633}
3634
3635Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3636 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3637 Exp->getLocEnd());
3638
3639 // Now do the actual rewrite.
3640 ReplaceStmt(Exp, ReplacingStmt);
3641
3642 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3643 return ReplacingStmt;
3644}
3645
3646// typedef struct objc_object Protocol;
3647QualType RewriteModernObjC::getProtocolType() {
3648 if (!ProtocolTypeDecl) {
3649 TypeSourceInfo *TInfo
3650 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3651 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3652 SourceLocation(), SourceLocation(),
3653 &Context->Idents.get("Protocol"),
3654 TInfo);
3655 }
3656 return Context->getTypeDeclType(ProtocolTypeDecl);
3657}
3658
3659/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3660/// a synthesized/forward data reference (to the protocol's metadata).
3661/// The forward references (and metadata) are generated in
3662/// RewriteModernObjC::HandleTranslationUnit().
3663Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003664 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3665 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003666 IdentifierInfo *ID = &Context->Idents.get(Name);
3667 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3668 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003669 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003670 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3671 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003672 CastExpr *castExpr =
3673 NoTypeInfoCStyleCastExpr(
3674 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003675 ReplaceStmt(Exp, castExpr);
3676 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3677 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3678 return castExpr;
3679
3680}
3681
3682bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3683 const char *endBuf) {
3684 while (startBuf < endBuf) {
3685 if (*startBuf == '#') {
3686 // Skip whitespace.
3687 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3688 ;
3689 if (!strncmp(startBuf, "if", strlen("if")) ||
3690 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3691 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3692 !strncmp(startBuf, "define", strlen("define")) ||
3693 !strncmp(startBuf, "undef", strlen("undef")) ||
3694 !strncmp(startBuf, "else", strlen("else")) ||
3695 !strncmp(startBuf, "elif", strlen("elif")) ||
3696 !strncmp(startBuf, "endif", strlen("endif")) ||
3697 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3698 !strncmp(startBuf, "include", strlen("include")) ||
3699 !strncmp(startBuf, "import", strlen("import")) ||
3700 !strncmp(startBuf, "include_next", strlen("include_next")))
3701 return true;
3702 }
3703 startBuf++;
3704 }
3705 return false;
3706}
3707
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003708/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3709/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003710bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003711 TagDecl *Tag,
3712 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003713 if (!IDecl)
3714 return false;
3715 SourceLocation TagLocation;
3716 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3717 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003718 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003719 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003720 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003721 TagLocation = RD->getLocation();
3722 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003723 IDecl->getLocation(), TagLocation);
3724 }
3725 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3726 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3727 return false;
3728 IsNamedDefinition = true;
3729 TagLocation = ED->getLocation();
3730 return Context->getSourceManager().isBeforeInTranslationUnit(
3731 IDecl->getLocation(), TagLocation);
3732
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003733 }
3734 return false;
3735}
3736
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003737/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003738/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003739bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3740 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003741 if (isa<TypedefType>(Type)) {
3742 Result += "\t";
3743 return false;
3744 }
3745
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003746 if (Type->isArrayType()) {
3747 QualType ElemTy = Context->getBaseElementType(Type);
3748 return RewriteObjCFieldDeclType(ElemTy, Result);
3749 }
3750 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003751 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3752 if (RD->isCompleteDefinition()) {
3753 if (RD->isStruct())
3754 Result += "\n\tstruct ";
3755 else if (RD->isUnion())
3756 Result += "\n\tunion ";
3757 else
3758 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003759
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003760 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003761 if (GlobalDefinedTags.count(RD)) {
3762 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003763 Result += " ";
3764 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003765 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003766 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003767 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003768 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003769 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003770 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003771 }
3772 }
3773 else if (Type->isEnumeralType()) {
3774 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3775 if (ED->isCompleteDefinition()) {
3776 Result += "\n\tenum ";
3777 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003778 if (GlobalDefinedTags.count(ED)) {
3779 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003780 Result += " ";
3781 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003782 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003783
3784 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003785 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003786 Result += "\t"; Result += EC->getName(); Result += " = ";
3787 llvm::APSInt Val = EC->getInitVal();
3788 Result += Val.toString(10);
3789 Result += ",\n";
3790 }
3791 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003792 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003793 }
3794 }
3795
3796 Result += "\t";
3797 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003798 return false;
3799}
3800
3801
3802/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3803/// It handles elaborated types, as well as enum types in the process.
3804void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3805 std::string &Result) {
3806 QualType Type = fieldDecl->getType();
3807 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003808
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003809 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3810 if (!EleboratedType)
3811 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003812 Result += Name;
3813 if (fieldDecl->isBitField()) {
3814 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3815 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003816 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003817 const ArrayType *AT = Context->getAsArrayType(Type);
3818 do {
3819 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003820 Result += "[";
3821 llvm::APInt Dim = CAT->getSize();
3822 Result += utostr(Dim.getZExtValue());
3823 Result += "]";
3824 }
Eli Friedman07bab732012-12-13 01:43:21 +00003825 AT = Context->getAsArrayType(AT->getElementType());
3826 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003827 }
3828
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003829 Result += ";\n";
3830}
3831
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003832/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3833/// named aggregate types into the input buffer.
3834void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3835 std::string &Result) {
3836 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003837 if (isa<TypedefType>(Type))
3838 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003839 if (Type->isArrayType())
3840 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003841 ObjCContainerDecl *IDecl =
3842 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003843
3844 TagDecl *TD = 0;
3845 if (Type->isRecordType()) {
3846 TD = Type->getAs<RecordType>()->getDecl();
3847 }
3848 else if (Type->isEnumeralType()) {
3849 TD = Type->getAs<EnumType>()->getDecl();
3850 }
3851
3852 if (TD) {
3853 if (GlobalDefinedTags.count(TD))
3854 return;
3855
3856 bool IsNamedDefinition = false;
3857 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3858 RewriteObjCFieldDeclType(Type, Result);
3859 Result += ";";
3860 }
3861 if (IsNamedDefinition)
3862 GlobalDefinedTags.insert(TD);
3863 }
3864
3865}
3866
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003867unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3868 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3869 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3870 return IvarGroupNumber[IV];
3871 }
3872 unsigned GroupNo = 0;
3873 SmallVector<const ObjCIvarDecl *, 8> IVars;
3874 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3875 IVD; IVD = IVD->getNextIvar())
3876 IVars.push_back(IVD);
3877
3878 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3879 if (IVars[i]->isBitField()) {
3880 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3881 while (i < e && IVars[i]->isBitField())
3882 IvarGroupNumber[IVars[i++]] = GroupNo;
3883 if (i < e)
3884 --i;
3885 }
3886
3887 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3888 return IvarGroupNumber[IV];
3889}
3890
3891QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3892 ObjCIvarDecl *IV,
3893 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3894 std::string StructTagName;
3895 ObjCIvarBitfieldGroupType(IV, StructTagName);
3896 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3897 Context->getTranslationUnitDecl(),
3898 SourceLocation(), SourceLocation(),
3899 &Context->Idents.get(StructTagName));
3900 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3901 ObjCIvarDecl *Ivar = IVars[i];
3902 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3903 &Context->Idents.get(Ivar->getName()),
3904 Ivar->getType(),
3905 0, /*Expr *BW */Ivar->getBitWidth(), false,
3906 ICIS_NoInit));
3907 }
3908 RD->completeDefinition();
3909 return Context->getTagDeclType(RD);
3910}
3911
3912QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3913 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3914 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3915 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3916 if (GroupRecordType.count(tuple))
3917 return GroupRecordType[tuple];
3918
3919 SmallVector<ObjCIvarDecl *, 8> IVars;
3920 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3921 IVD; IVD = IVD->getNextIvar()) {
3922 if (IVD->isBitField())
3923 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3924 else {
3925 if (!IVars.empty()) {
3926 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3927 // Generate the struct type for this group of bitfield ivars.
3928 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3929 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3930 IVars.clear();
3931 }
3932 }
3933 }
3934 if (!IVars.empty()) {
3935 // Do the last one.
3936 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3937 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3938 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3939 }
3940 QualType RetQT = GroupRecordType[tuple];
3941 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3942
3943 return RetQT;
3944}
3945
3946/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3947/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3948void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3949 std::string &Result) {
3950 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3951 Result += CDecl->getName();
3952 Result += "__GRBF_";
3953 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3954 Result += utostr(GroupNo);
3955 return;
3956}
3957
3958/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3959/// Name of the struct would be: classname__T_n where n is the group number for
3960/// this ivar.
3961void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3962 std::string &Result) {
3963 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3964 Result += CDecl->getName();
3965 Result += "__T_";
3966 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3967 Result += utostr(GroupNo);
3968 return;
3969}
3970
3971/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3972/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3973/// this ivar.
3974void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3975 std::string &Result) {
3976 Result += "OBJC_IVAR_$_";
3977 ObjCIvarBitfieldGroupDecl(IV, Result);
3978}
3979
3980#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3981 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3982 ++IX; \
3983 if (IX < ENDIX) \
3984 --IX; \
3985}
3986
Fariborz Jahanian11671902012-02-07 17:11:38 +00003987/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3988/// an objective-c class with ivars.
3989void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3990 std::string &Result) {
3991 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3992 assert(CDecl->getName() != "" &&
3993 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003994 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003995 SmallVector<ObjCIvarDecl *, 8> IVars;
3996 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003997 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003998 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003999
Fariborz Jahanian11671902012-02-07 17:11:38 +00004000 SourceLocation LocStart = CDecl->getLocStart();
4001 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004002
Fariborz Jahanian11671902012-02-07 17:11:38 +00004003 const char *startBuf = SM->getCharacterData(LocStart);
4004 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004005
Fariborz Jahanian11671902012-02-07 17:11:38 +00004006 // If no ivars and no root or if its root, directly or indirectly,
4007 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004008 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004009 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4010 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4011 ReplaceText(LocStart, endBuf-startBuf, Result);
4012 return;
4013 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004014
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004015 // Insert named struct/union definitions inside class to
4016 // outer scope. This follows semantics of locally defined
4017 // struct/unions in objective-c classes.
4018 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4019 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004020
4021 // Insert named structs which are syntheized to group ivar bitfields
4022 // to outer scope as well.
4023 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4024 if (IVars[i]->isBitField()) {
4025 ObjCIvarDecl *IV = IVars[i];
4026 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4027 RewriteObjCFieldDeclType(QT, Result);
4028 Result += ";";
4029 // skip over ivar bitfields in this group.
4030 SKIP_BITFIELDS(i , e, IVars);
4031 }
4032
Fariborz Jahanian11671902012-02-07 17:11:38 +00004033 Result += "\nstruct ";
4034 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004035 Result += "_IMPL {\n";
4036
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004037 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004038 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4039 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4040 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004041 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004042
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004043 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4044 if (IVars[i]->isBitField()) {
4045 ObjCIvarDecl *IV = IVars[i];
4046 Result += "\tstruct ";
4047 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4048 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4049 // skip over ivar bitfields in this group.
4050 SKIP_BITFIELDS(i , e, IVars);
4051 }
4052 else
4053 RewriteObjCFieldDecl(IVars[i], Result);
4054 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004055
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004056 Result += "};\n";
4057 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4058 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004059 // Mark this struct as having been generated.
4060 if (!ObjCSynthesizedStructs.insert(CDecl))
4061 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004062}
4063
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004064/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4065/// have been referenced in an ivar access expression.
4066void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4067 std::string &Result) {
4068 // write out ivar offset symbols which have been referenced in an ivar
4069 // access expression.
4070 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4071 if (Ivars.empty())
4072 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004073
4074 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004075 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4076 e = Ivars.end(); i != e; i++) {
4077 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004078 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4079 unsigned GroupNo = 0;
4080 if (IvarDecl->isBitField()) {
4081 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4082 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4083 continue;
4084 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004085 Result += "\n";
4086 if (LangOpts.MicrosoftExt)
4087 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004088 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004089 if (LangOpts.MicrosoftExt &&
4090 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004091 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4092 Result += "__declspec(dllimport) ";
4093
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004094 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004095 if (IvarDecl->isBitField()) {
4096 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4097 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4098 }
4099 else
4100 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004101 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004102 }
4103}
4104
Fariborz Jahanian11671902012-02-07 17:11:38 +00004105//===----------------------------------------------------------------------===//
4106// Meta Data Emission
4107//===----------------------------------------------------------------------===//
4108
4109
4110/// RewriteImplementations - This routine rewrites all method implementations
4111/// and emits meta-data.
4112
4113void RewriteModernObjC::RewriteImplementations() {
4114 int ClsDefCount = ClassImplementation.size();
4115 int CatDefCount = CategoryImplementation.size();
4116
4117 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004118 for (int i = 0; i < ClsDefCount; i++) {
4119 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4120 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4121 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004122 assert(false &&
4123 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004124 RewriteImplementationDecl(OIMP);
4125 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004126
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004127 for (int i = 0; i < CatDefCount; i++) {
4128 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4129 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4130 if (CDecl->isImplicitInterfaceDecl())
4131 assert(false &&
4132 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004133 RewriteImplementationDecl(CIMP);
4134 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004135}
4136
4137void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4138 const std::string &Name,
4139 ValueDecl *VD, bool def) {
4140 assert(BlockByRefDeclNo.count(VD) &&
4141 "RewriteByRefString: ByRef decl missing");
4142 if (def)
4143 ResultStr += "struct ";
4144 ResultStr += "__Block_byref_" + Name +
4145 "_" + utostr(BlockByRefDeclNo[VD]) ;
4146}
4147
4148static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4149 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4150 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4151 return false;
4152}
4153
4154std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4155 StringRef funcName,
4156 std::string Tag) {
4157 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004158 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004159 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004160 SourceLocation BlockLoc = CE->getExprLoc();
4161 std::string S;
4162 ConvertSourceLocationToLineDirective(BlockLoc, S);
4163
4164 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4165 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004166
4167 BlockDecl *BD = CE->getBlockDecl();
4168
4169 if (isa<FunctionNoProtoType>(AFT)) {
4170 // No user-supplied arguments. Still need to pass in a pointer to the
4171 // block (to reference imported block decl refs).
4172 S += "(" + StructRef + " *__cself)";
4173 } else if (BD->param_empty()) {
4174 S += "(" + StructRef + " *__cself)";
4175 } else {
4176 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4177 assert(FT && "SynthesizeBlockFunc: No function proto");
4178 S += '(';
4179 // first add the implicit argument.
4180 S += StructRef + " *__cself, ";
4181 std::string ParamStr;
4182 for (BlockDecl::param_iterator AI = BD->param_begin(),
4183 E = BD->param_end(); AI != E; ++AI) {
4184 if (AI != BD->param_begin()) S += ", ";
4185 ParamStr = (*AI)->getNameAsString();
4186 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004187 (void)convertBlockPointerToFunctionPointer(QT);
4188 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004189 S += ParamStr;
4190 }
4191 if (FT->isVariadic()) {
4192 if (!BD->param_empty()) S += ", ";
4193 S += "...";
4194 }
4195 S += ')';
4196 }
4197 S += " {\n";
4198
4199 // Create local declarations to avoid rewriting all closure decl ref exprs.
4200 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004201 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004202 E = BlockByRefDecls.end(); I != E; ++I) {
4203 S += " ";
4204 std::string Name = (*I)->getNameAsString();
4205 std::string TypeString;
4206 RewriteByRefString(TypeString, Name, (*I));
4207 TypeString += " *";
4208 Name = TypeString + Name;
4209 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4210 }
4211 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004212 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004213 E = BlockByCopyDecls.end(); I != E; ++I) {
4214 S += " ";
4215 // Handle nested closure invocation. For example:
4216 //
4217 // void (^myImportedClosure)(void);
4218 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4219 //
4220 // void (^anotherClosure)(void);
4221 // anotherClosure = ^(void) {
4222 // myImportedClosure(); // import and invoke the closure
4223 // };
4224 //
4225 if (isTopLevelBlockPointerType((*I)->getType())) {
4226 RewriteBlockPointerTypeVariable(S, (*I));
4227 S += " = (";
4228 RewriteBlockPointerType(S, (*I)->getType());
4229 S += ")";
4230 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4231 }
4232 else {
4233 std::string Name = (*I)->getNameAsString();
4234 QualType QT = (*I)->getType();
4235 if (HasLocalVariableExternalStorage(*I))
4236 QT = Context->getPointerType(QT);
4237 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4238 S += Name + " = __cself->" +
4239 (*I)->getNameAsString() + "; // bound by copy\n";
4240 }
4241 }
4242 std::string RewrittenStr = RewrittenBlockExprs[CE];
4243 const char *cstr = RewrittenStr.c_str();
4244 while (*cstr++ != '{') ;
4245 S += cstr;
4246 S += "\n";
4247 return S;
4248}
4249
4250std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4251 StringRef funcName,
4252 std::string Tag) {
4253 std::string StructRef = "struct " + Tag;
4254 std::string S = "static void __";
4255
4256 S += funcName;
4257 S += "_block_copy_" + utostr(i);
4258 S += "(" + StructRef;
4259 S += "*dst, " + StructRef;
4260 S += "*src) {";
4261 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4262 E = ImportedBlockDecls.end(); I != E; ++I) {
4263 ValueDecl *VD = (*I);
4264 S += "_Block_object_assign((void*)&dst->";
4265 S += (*I)->getNameAsString();
4266 S += ", (void*)src->";
4267 S += (*I)->getNameAsString();
4268 if (BlockByRefDeclsPtrSet.count((*I)))
4269 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4270 else if (VD->getType()->isBlockPointerType())
4271 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4272 else
4273 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4274 }
4275 S += "}\n";
4276
4277 S += "\nstatic void __";
4278 S += funcName;
4279 S += "_block_dispose_" + utostr(i);
4280 S += "(" + StructRef;
4281 S += "*src) {";
4282 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4283 E = ImportedBlockDecls.end(); I != E; ++I) {
4284 ValueDecl *VD = (*I);
4285 S += "_Block_object_dispose((void*)src->";
4286 S += (*I)->getNameAsString();
4287 if (BlockByRefDeclsPtrSet.count((*I)))
4288 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4289 else if (VD->getType()->isBlockPointerType())
4290 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4291 else
4292 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4293 }
4294 S += "}\n";
4295 return S;
4296}
4297
4298std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4299 std::string Desc) {
4300 std::string S = "\nstruct " + Tag;
4301 std::string Constructor = " " + Tag;
4302
4303 S += " {\n struct __block_impl impl;\n";
4304 S += " struct " + Desc;
4305 S += "* Desc;\n";
4306
4307 Constructor += "(void *fp, "; // Invoke function pointer.
4308 Constructor += "struct " + Desc; // Descriptor pointer.
4309 Constructor += " *desc";
4310
4311 if (BlockDeclRefs.size()) {
4312 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004313 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004314 E = BlockByCopyDecls.end(); I != E; ++I) {
4315 S += " ";
4316 std::string FieldName = (*I)->getNameAsString();
4317 std::string ArgName = "_" + FieldName;
4318 // Handle nested closure invocation. For example:
4319 //
4320 // void (^myImportedBlock)(void);
4321 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4322 //
4323 // void (^anotherBlock)(void);
4324 // anotherBlock = ^(void) {
4325 // myImportedBlock(); // import and invoke the closure
4326 // };
4327 //
4328 if (isTopLevelBlockPointerType((*I)->getType())) {
4329 S += "struct __block_impl *";
4330 Constructor += ", void *" + ArgName;
4331 } else {
4332 QualType QT = (*I)->getType();
4333 if (HasLocalVariableExternalStorage(*I))
4334 QT = Context->getPointerType(QT);
4335 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4336 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4337 Constructor += ", " + ArgName;
4338 }
4339 S += FieldName + ";\n";
4340 }
4341 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004342 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004343 E = BlockByRefDecls.end(); I != E; ++I) {
4344 S += " ";
4345 std::string FieldName = (*I)->getNameAsString();
4346 std::string ArgName = "_" + FieldName;
4347 {
4348 std::string TypeString;
4349 RewriteByRefString(TypeString, FieldName, (*I));
4350 TypeString += " *";
4351 FieldName = TypeString + FieldName;
4352 ArgName = TypeString + ArgName;
4353 Constructor += ", " + ArgName;
4354 }
4355 S += FieldName + "; // by ref\n";
4356 }
4357 // Finish writing the constructor.
4358 Constructor += ", int flags=0)";
4359 // Initialize all "by copy" arguments.
4360 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004361 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004362 E = BlockByCopyDecls.end(); I != E; ++I) {
4363 std::string Name = (*I)->getNameAsString();
4364 if (firsTime) {
4365 Constructor += " : ";
4366 firsTime = false;
4367 }
4368 else
4369 Constructor += ", ";
4370 if (isTopLevelBlockPointerType((*I)->getType()))
4371 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4372 else
4373 Constructor += Name + "(_" + Name + ")";
4374 }
4375 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004376 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004377 E = BlockByRefDecls.end(); I != E; ++I) {
4378 std::string Name = (*I)->getNameAsString();
4379 if (firsTime) {
4380 Constructor += " : ";
4381 firsTime = false;
4382 }
4383 else
4384 Constructor += ", ";
4385 Constructor += Name + "(_" + Name + "->__forwarding)";
4386 }
4387
4388 Constructor += " {\n";
4389 if (GlobalVarDecl)
4390 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4391 else
4392 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4393 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4394
4395 Constructor += " Desc = desc;\n";
4396 } else {
4397 // Finish writing the constructor.
4398 Constructor += ", int flags=0) {\n";
4399 if (GlobalVarDecl)
4400 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4401 else
4402 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4403 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4404 Constructor += " Desc = desc;\n";
4405 }
4406 Constructor += " ";
4407 Constructor += "}\n";
4408 S += Constructor;
4409 S += "};\n";
4410 return S;
4411}
4412
4413std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4414 std::string ImplTag, int i,
4415 StringRef FunName,
4416 unsigned hasCopy) {
4417 std::string S = "\nstatic struct " + DescTag;
4418
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004419 S += " {\n size_t reserved;\n";
4420 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004421 if (hasCopy) {
4422 S += " void (*copy)(struct ";
4423 S += ImplTag; S += "*, struct ";
4424 S += ImplTag; S += "*);\n";
4425
4426 S += " void (*dispose)(struct ";
4427 S += ImplTag; S += "*);\n";
4428 }
4429 S += "} ";
4430
4431 S += DescTag + "_DATA = { 0, sizeof(struct ";
4432 S += ImplTag + ")";
4433 if (hasCopy) {
4434 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4435 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4436 }
4437 S += "};\n";
4438 return S;
4439}
4440
4441void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4442 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004443 bool RewriteSC = (GlobalVarDecl &&
4444 !Blocks.empty() &&
4445 GlobalVarDecl->getStorageClass() == SC_Static &&
4446 GlobalVarDecl->getType().getCVRQualifiers());
4447 if (RewriteSC) {
4448 std::string SC(" void __");
4449 SC += GlobalVarDecl->getNameAsString();
4450 SC += "() {}";
4451 InsertText(FunLocStart, SC);
4452 }
4453
4454 // Insert closures that were part of the function.
4455 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4456 CollectBlockDeclRefInfo(Blocks[i]);
4457 // Need to copy-in the inner copied-in variables not actually used in this
4458 // block.
4459 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004460 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004461 ValueDecl *VD = Exp->getDecl();
4462 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004463 if (!VD->hasAttr<BlocksAttr>()) {
4464 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4465 BlockByCopyDeclsPtrSet.insert(VD);
4466 BlockByCopyDecls.push_back(VD);
4467 }
4468 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004469 }
John McCall113bee02012-03-10 09:33:50 +00004470
4471 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004472 BlockByRefDeclsPtrSet.insert(VD);
4473 BlockByRefDecls.push_back(VD);
4474 }
John McCall113bee02012-03-10 09:33:50 +00004475
Fariborz Jahanian11671902012-02-07 17:11:38 +00004476 // imported objects in the inner blocks not used in the outer
4477 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004478 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004479 VD->getType()->isBlockPointerType())
4480 ImportedBlockDecls.insert(VD);
4481 }
4482
4483 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4484 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4485
4486 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4487
4488 InsertText(FunLocStart, CI);
4489
4490 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4491
4492 InsertText(FunLocStart, CF);
4493
4494 if (ImportedBlockDecls.size()) {
4495 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4496 InsertText(FunLocStart, HF);
4497 }
4498 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4499 ImportedBlockDecls.size() > 0);
4500 InsertText(FunLocStart, BD);
4501
4502 BlockDeclRefs.clear();
4503 BlockByRefDecls.clear();
4504 BlockByRefDeclsPtrSet.clear();
4505 BlockByCopyDecls.clear();
4506 BlockByCopyDeclsPtrSet.clear();
4507 ImportedBlockDecls.clear();
4508 }
4509 if (RewriteSC) {
4510 // Must insert any 'const/volatile/static here. Since it has been
4511 // removed as result of rewriting of block literals.
4512 std::string SC;
4513 if (GlobalVarDecl->getStorageClass() == SC_Static)
4514 SC = "static ";
4515 if (GlobalVarDecl->getType().isConstQualified())
4516 SC += "const ";
4517 if (GlobalVarDecl->getType().isVolatileQualified())
4518 SC += "volatile ";
4519 if (GlobalVarDecl->getType().isRestrictQualified())
4520 SC += "restrict ";
4521 InsertText(FunLocStart, SC);
4522 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004523 if (GlobalConstructionExp) {
4524 // extra fancy dance for global literal expression.
4525
4526 // Always the latest block expression on the block stack.
4527 std::string Tag = "__";
4528 Tag += FunName;
4529 Tag += "_block_impl_";
4530 Tag += utostr(Blocks.size()-1);
4531 std::string globalBuf = "static ";
4532 globalBuf += Tag; globalBuf += " ";
4533 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004534
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004535 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004536 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004537 PrintingPolicy(LangOpts));
4538 globalBuf += constructorExprBuf.str();
4539 globalBuf += ";\n";
4540 InsertText(FunLocStart, globalBuf);
4541 GlobalConstructionExp = 0;
4542 }
4543
Fariborz Jahanian11671902012-02-07 17:11:38 +00004544 Blocks.clear();
4545 InnerDeclRefsCount.clear();
4546 InnerDeclRefs.clear();
4547 RewrittenBlockExprs.clear();
4548}
4549
4550void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004551 SourceLocation FunLocStart =
4552 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4553 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004554 StringRef FuncName = FD->getName();
4555
4556 SynthesizeBlockLiterals(FunLocStart, FuncName);
4557}
4558
4559static void BuildUniqueMethodName(std::string &Name,
4560 ObjCMethodDecl *MD) {
4561 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4562 Name = IFace->getName();
4563 Name += "__" + MD->getSelector().getAsString();
4564 // Convert colons to underscores.
4565 std::string::size_type loc = 0;
4566 while ((loc = Name.find(":", loc)) != std::string::npos)
4567 Name.replace(loc, 1, "_");
4568}
4569
4570void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4571 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4572 //SourceLocation FunLocStart = MD->getLocStart();
4573 SourceLocation FunLocStart = MD->getLocStart();
4574 std::string FuncName;
4575 BuildUniqueMethodName(FuncName, MD);
4576 SynthesizeBlockLiterals(FunLocStart, FuncName);
4577}
4578
4579void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4580 for (Stmt::child_range CI = S->children(); CI; ++CI)
4581 if (*CI) {
4582 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4583 GetBlockDeclRefExprs(CBE->getBody());
4584 else
4585 GetBlockDeclRefExprs(*CI);
4586 }
4587 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004588 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4589 if (DRE->refersToEnclosingLocal()) {
4590 // FIXME: Handle enums.
4591 if (!isa<FunctionDecl>(DRE->getDecl()))
4592 BlockDeclRefs.push_back(DRE);
4593 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4594 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004595 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004596 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004597
4598 return;
4599}
4600
Craig Topper5603df42013-07-05 19:34:19 +00004601void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4602 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004603 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4604 for (Stmt::child_range CI = S->children(); CI; ++CI)
4605 if (*CI) {
4606 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4607 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4608 GetInnerBlockDeclRefExprs(CBE->getBody(),
4609 InnerBlockDeclRefs,
4610 InnerContexts);
4611 }
4612 else
4613 GetInnerBlockDeclRefExprs(*CI,
4614 InnerBlockDeclRefs,
4615 InnerContexts);
4616
4617 }
4618 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004619 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4620 if (DRE->refersToEnclosingLocal()) {
4621 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4622 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4623 InnerBlockDeclRefs.push_back(DRE);
4624 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4625 if (Var->isFunctionOrMethodVarDecl())
4626 ImportedLocalExternalDecls.insert(Var);
4627 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004628 }
4629
4630 return;
4631}
4632
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004633/// convertObjCTypeToCStyleType - This routine converts such objc types
4634/// as qualified objects, and blocks to their closest c/c++ types that
4635/// it can. It returns true if input type was modified.
4636bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4637 QualType oldT = T;
4638 convertBlockPointerToFunctionPointer(T);
4639 if (T->isFunctionPointerType()) {
4640 QualType PointeeTy;
4641 if (const PointerType* PT = T->getAs<PointerType>()) {
4642 PointeeTy = PT->getPointeeType();
4643 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4644 T = convertFunctionTypeOfBlocks(FT);
4645 T = Context->getPointerType(T);
4646 }
4647 }
4648 }
4649
4650 convertToUnqualifiedObjCType(T);
4651 return T != oldT;
4652}
4653
Fariborz Jahanian11671902012-02-07 17:11:38 +00004654/// convertFunctionTypeOfBlocks - This routine converts a function type
4655/// whose result type may be a block pointer or whose argument type(s)
4656/// might be block pointers to an equivalent function type replacing
4657/// all block pointers to function pointers.
4658QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4659 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4660 // FTP will be null for closures that don't take arguments.
4661 // Generate a funky cast.
4662 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004663 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004664 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004665
4666 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004667 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4668 E = FTP->param_type_end();
4669 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004670 QualType t = *I;
4671 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004672 if (convertObjCTypeToCStyleType(t))
4673 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004674 ArgTypes.push_back(t);
4675 }
4676 }
4677 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004678 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004679 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004680 else FuncType = QualType(FT, 0);
4681 return FuncType;
4682}
4683
4684Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4685 // Navigate to relevant type information.
4686 const BlockPointerType *CPT = 0;
4687
4688 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4689 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004690 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4691 CPT = MExpr->getType()->getAs<BlockPointerType>();
4692 }
4693 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4694 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4695 }
4696 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4697 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4698 else if (const ConditionalOperator *CEXPR =
4699 dyn_cast<ConditionalOperator>(BlockExp)) {
4700 Expr *LHSExp = CEXPR->getLHS();
4701 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4702 Expr *RHSExp = CEXPR->getRHS();
4703 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4704 Expr *CONDExp = CEXPR->getCond();
4705 ConditionalOperator *CondExpr =
4706 new (Context) ConditionalOperator(CONDExp,
4707 SourceLocation(), cast<Expr>(LHSStmt),
4708 SourceLocation(), cast<Expr>(RHSStmt),
4709 Exp->getType(), VK_RValue, OK_Ordinary);
4710 return CondExpr;
4711 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4712 CPT = IRE->getType()->getAs<BlockPointerType>();
4713 } else if (const PseudoObjectExpr *POE
4714 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4715 CPT = POE->getType()->castAs<BlockPointerType>();
4716 } else {
4717 assert(1 && "RewriteBlockClass: Bad type");
4718 }
4719 assert(CPT && "RewriteBlockClass: Bad type");
4720 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4721 assert(FT && "RewriteBlockClass: Bad type");
4722 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4723 // FTP will be null for closures that don't take arguments.
4724
4725 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4726 SourceLocation(), SourceLocation(),
4727 &Context->Idents.get("__block_impl"));
4728 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4729
4730 // Generate a funky cast.
4731 SmallVector<QualType, 8> ArgTypes;
4732
4733 // Push the block argument type.
4734 ArgTypes.push_back(PtrBlock);
4735 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004736 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4737 E = FTP->param_type_end();
4738 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004739 QualType t = *I;
4740 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4741 if (!convertBlockPointerToFunctionPointer(t))
4742 convertToUnqualifiedObjCType(t);
4743 ArgTypes.push_back(t);
4744 }
4745 }
4746 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004747 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004748
4749 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4750
4751 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4752 CK_BitCast,
4753 const_cast<Expr*>(BlockExp));
4754 // Don't forget the parens to enforce the proper binding.
4755 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4756 BlkCast);
4757 //PE->dump();
4758
4759 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4760 SourceLocation(),
4761 &Context->Idents.get("FuncPtr"),
4762 Context->VoidPtrTy, 0,
4763 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004764 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004765 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4766 FD->getType(), VK_LValue,
4767 OK_Ordinary);
4768
4769
4770 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4771 CK_BitCast, ME);
4772 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4773
4774 SmallVector<Expr*, 8> BlkExprs;
4775 // Add the implicit argument.
4776 BlkExprs.push_back(BlkCast);
4777 // Add the user arguments.
4778 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4779 E = Exp->arg_end(); I != E; ++I) {
4780 BlkExprs.push_back(*I);
4781 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004782 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004783 Exp->getType(), VK_RValue,
4784 SourceLocation());
4785 return CE;
4786}
4787
4788// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004789// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004790// For example:
4791//
4792// int main() {
4793// __block Foo *f;
4794// __block int i;
4795//
4796// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004797// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004798// i = 77;
4799// };
4800//}
John McCall113bee02012-03-10 09:33:50 +00004801Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004802 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4803 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004804 ValueDecl *VD = DeclRefExp->getDecl();
4805 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004806
4807 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4808 SourceLocation(),
4809 &Context->Idents.get("__forwarding"),
4810 Context->VoidPtrTy, 0,
4811 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004812 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004813 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4814 FD, SourceLocation(),
4815 FD->getType(), VK_LValue,
4816 OK_Ordinary);
4817
4818 StringRef Name = VD->getName();
4819 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4820 &Context->Idents.get(Name),
4821 Context->VoidPtrTy, 0,
4822 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004823 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004824 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4825 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4826
4827
4828
4829 // Need parens to enforce precedence.
4830 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4831 DeclRefExp->getExprLoc(),
4832 ME);
4833 ReplaceStmt(DeclRefExp, PE);
4834 return PE;
4835}
4836
4837// Rewrites the imported local variable V with external storage
4838// (static, extern, etc.) as *V
4839//
4840Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4841 ValueDecl *VD = DRE->getDecl();
4842 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4843 if (!ImportedLocalExternalDecls.count(Var))
4844 return DRE;
4845 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4846 VK_LValue, OK_Ordinary,
4847 DRE->getLocation());
4848 // Need parens to enforce precedence.
4849 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4850 Exp);
4851 ReplaceStmt(DRE, PE);
4852 return PE;
4853}
4854
4855void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4856 SourceLocation LocStart = CE->getLParenLoc();
4857 SourceLocation LocEnd = CE->getRParenLoc();
4858
4859 // Need to avoid trying to rewrite synthesized casts.
4860 if (LocStart.isInvalid())
4861 return;
4862 // Need to avoid trying to rewrite casts contained in macros.
4863 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4864 return;
4865
4866 const char *startBuf = SM->getCharacterData(LocStart);
4867 const char *endBuf = SM->getCharacterData(LocEnd);
4868 QualType QT = CE->getType();
4869 const Type* TypePtr = QT->getAs<Type>();
4870 if (isa<TypeOfExprType>(TypePtr)) {
4871 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4872 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4873 std::string TypeAsString = "(";
4874 RewriteBlockPointerType(TypeAsString, QT);
4875 TypeAsString += ")";
4876 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4877 return;
4878 }
4879 // advance the location to startArgList.
4880 const char *argPtr = startBuf;
4881
4882 while (*argPtr++ && (argPtr < endBuf)) {
4883 switch (*argPtr) {
4884 case '^':
4885 // Replace the '^' with '*'.
4886 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4887 ReplaceText(LocStart, 1, "*");
4888 break;
4889 }
4890 }
4891 return;
4892}
4893
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004894void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4895 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004896 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4897 CastKind != CK_AnyPointerToBlockPointerCast)
4898 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004899
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004900 QualType QT = IC->getType();
4901 (void)convertBlockPointerToFunctionPointer(QT);
4902 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4903 std::string Str = "(";
4904 Str += TypeString;
4905 Str += ")";
4906 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4907
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004908 return;
4909}
4910
Fariborz Jahanian11671902012-02-07 17:11:38 +00004911void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4912 SourceLocation DeclLoc = FD->getLocation();
4913 unsigned parenCount = 0;
4914
4915 // We have 1 or more arguments that have closure pointers.
4916 const char *startBuf = SM->getCharacterData(DeclLoc);
4917 const char *startArgList = strchr(startBuf, '(');
4918
4919 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4920
4921 parenCount++;
4922 // advance the location to startArgList.
4923 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4924 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4925
4926 const char *argPtr = startArgList;
4927
4928 while (*argPtr++ && parenCount) {
4929 switch (*argPtr) {
4930 case '^':
4931 // Replace the '^' with '*'.
4932 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4933 ReplaceText(DeclLoc, 1, "*");
4934 break;
4935 case '(':
4936 parenCount++;
4937 break;
4938 case ')':
4939 parenCount--;
4940 break;
4941 }
4942 }
4943 return;
4944}
4945
4946bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4947 const FunctionProtoType *FTP;
4948 const PointerType *PT = QT->getAs<PointerType>();
4949 if (PT) {
4950 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4951 } else {
4952 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4953 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4954 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4955 }
4956 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004957 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4958 E = FTP->param_type_end();
4959 I != E; ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004960 if (isTopLevelBlockPointerType(*I))
4961 return true;
4962 }
4963 return false;
4964}
4965
4966bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4967 const FunctionProtoType *FTP;
4968 const PointerType *PT = QT->getAs<PointerType>();
4969 if (PT) {
4970 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4971 } else {
4972 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4973 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4974 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4975 }
4976 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004977 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4978 E = FTP->param_type_end();
4979 I != E; ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004980 if ((*I)->isObjCQualifiedIdType())
4981 return true;
4982 if ((*I)->isObjCObjectPointerType() &&
4983 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4984 return true;
4985 }
4986
4987 }
4988 return false;
4989}
4990
4991void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4992 const char *&RParen) {
4993 const char *argPtr = strchr(Name, '(');
4994 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4995
4996 LParen = argPtr; // output the start.
4997 argPtr++; // skip past the left paren.
4998 unsigned parenCount = 1;
4999
5000 while (*argPtr && parenCount) {
5001 switch (*argPtr) {
5002 case '(': parenCount++; break;
5003 case ')': parenCount--; break;
5004 default: break;
5005 }
5006 if (parenCount) argPtr++;
5007 }
5008 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5009 RParen = argPtr; // output the end
5010}
5011
5012void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5013 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5014 RewriteBlockPointerFunctionArgs(FD);
5015 return;
5016 }
5017 // Handle Variables and Typedefs.
5018 SourceLocation DeclLoc = ND->getLocation();
5019 QualType DeclT;
5020 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5021 DeclT = VD->getType();
5022 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5023 DeclT = TDD->getUnderlyingType();
5024 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5025 DeclT = FD->getType();
5026 else
5027 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5028
5029 const char *startBuf = SM->getCharacterData(DeclLoc);
5030 const char *endBuf = startBuf;
5031 // scan backward (from the decl location) for the end of the previous decl.
5032 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5033 startBuf--;
5034 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5035 std::string buf;
5036 unsigned OrigLength=0;
5037 // *startBuf != '^' if we are dealing with a pointer to function that
5038 // may take block argument types (which will be handled below).
5039 if (*startBuf == '^') {
5040 // Replace the '^' with '*', computing a negative offset.
5041 buf = '*';
5042 startBuf++;
5043 OrigLength++;
5044 }
5045 while (*startBuf != ')') {
5046 buf += *startBuf;
5047 startBuf++;
5048 OrigLength++;
5049 }
5050 buf += ')';
5051 OrigLength++;
5052
5053 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5054 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5055 // Replace the '^' with '*' for arguments.
5056 // Replace id<P> with id/*<>*/
5057 DeclLoc = ND->getLocation();
5058 startBuf = SM->getCharacterData(DeclLoc);
5059 const char *argListBegin, *argListEnd;
5060 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5061 while (argListBegin < argListEnd) {
5062 if (*argListBegin == '^')
5063 buf += '*';
5064 else if (*argListBegin == '<') {
5065 buf += "/*";
5066 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005067 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005068 while (*argListBegin != '>') {
5069 buf += *argListBegin++;
5070 OrigLength++;
5071 }
5072 buf += *argListBegin;
5073 buf += "*/";
5074 }
5075 else
5076 buf += *argListBegin;
5077 argListBegin++;
5078 OrigLength++;
5079 }
5080 buf += ')';
5081 OrigLength++;
5082 }
5083 ReplaceText(Start, OrigLength, buf);
5084
5085 return;
5086}
5087
5088
5089/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5090/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5091/// struct Block_byref_id_object *src) {
5092/// _Block_object_assign (&_dest->object, _src->object,
5093/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5094/// [|BLOCK_FIELD_IS_WEAK]) // object
5095/// _Block_object_assign(&_dest->object, _src->object,
5096/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5097/// [|BLOCK_FIELD_IS_WEAK]) // block
5098/// }
5099/// And:
5100/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5101/// _Block_object_dispose(_src->object,
5102/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5103/// [|BLOCK_FIELD_IS_WEAK]) // object
5104/// _Block_object_dispose(_src->object,
5105/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5106/// [|BLOCK_FIELD_IS_WEAK]) // block
5107/// }
5108
5109std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5110 int flag) {
5111 std::string S;
5112 if (CopyDestroyCache.count(flag))
5113 return S;
5114 CopyDestroyCache.insert(flag);
5115 S = "static void __Block_byref_id_object_copy_";
5116 S += utostr(flag);
5117 S += "(void *dst, void *src) {\n";
5118
5119 // offset into the object pointer is computed as:
5120 // void * + void* + int + int + void* + void *
5121 unsigned IntSize =
5122 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5123 unsigned VoidPtrSize =
5124 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5125
5126 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5127 S += " _Block_object_assign((char*)dst + ";
5128 S += utostr(offset);
5129 S += ", *(void * *) ((char*)src + ";
5130 S += utostr(offset);
5131 S += "), ";
5132 S += utostr(flag);
5133 S += ");\n}\n";
5134
5135 S += "static void __Block_byref_id_object_dispose_";
5136 S += utostr(flag);
5137 S += "(void *src) {\n";
5138 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5139 S += utostr(offset);
5140 S += "), ";
5141 S += utostr(flag);
5142 S += ");\n}\n";
5143 return S;
5144}
5145
5146/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5147/// the declaration into:
5148/// struct __Block_byref_ND {
5149/// void *__isa; // NULL for everything except __weak pointers
5150/// struct __Block_byref_ND *__forwarding;
5151/// int32_t __flags;
5152/// int32_t __size;
5153/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5154/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5155/// typex ND;
5156/// };
5157///
5158/// It then replaces declaration of ND variable with:
5159/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5160/// __size=sizeof(struct __Block_byref_ND),
5161/// ND=initializer-if-any};
5162///
5163///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005164void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5165 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005166 int flag = 0;
5167 int isa = 0;
5168 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5169 if (DeclLoc.isInvalid())
5170 // If type location is missing, it is because of missing type (a warning).
5171 // Use variable's location which is good for this case.
5172 DeclLoc = ND->getLocation();
5173 const char *startBuf = SM->getCharacterData(DeclLoc);
5174 SourceLocation X = ND->getLocEnd();
5175 X = SM->getExpansionLoc(X);
5176 const char *endBuf = SM->getCharacterData(X);
5177 std::string Name(ND->getNameAsString());
5178 std::string ByrefType;
5179 RewriteByRefString(ByrefType, Name, ND, true);
5180 ByrefType += " {\n";
5181 ByrefType += " void *__isa;\n";
5182 RewriteByRefString(ByrefType, Name, ND);
5183 ByrefType += " *__forwarding;\n";
5184 ByrefType += " int __flags;\n";
5185 ByrefType += " int __size;\n";
5186 // Add void *__Block_byref_id_object_copy;
5187 // void *__Block_byref_id_object_dispose; if needed.
5188 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005189 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005190 if (HasCopyAndDispose) {
5191 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5192 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5193 }
5194
5195 QualType T = Ty;
5196 (void)convertBlockPointerToFunctionPointer(T);
5197 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5198
5199 ByrefType += " " + Name + ";\n";
5200 ByrefType += "};\n";
5201 // Insert this type in global scope. It is needed by helper function.
5202 SourceLocation FunLocStart;
5203 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005204 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005205 else {
5206 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5207 FunLocStart = CurMethodDef->getLocStart();
5208 }
5209 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005210
Fariborz Jahanian11671902012-02-07 17:11:38 +00005211 if (Ty.isObjCGCWeak()) {
5212 flag |= BLOCK_FIELD_IS_WEAK;
5213 isa = 1;
5214 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005215 if (HasCopyAndDispose) {
5216 flag = BLOCK_BYREF_CALLER;
5217 QualType Ty = ND->getType();
5218 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5219 if (Ty->isBlockPointerType())
5220 flag |= BLOCK_FIELD_IS_BLOCK;
5221 else
5222 flag |= BLOCK_FIELD_IS_OBJECT;
5223 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5224 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005225 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005226 }
5227
5228 // struct __Block_byref_ND ND =
5229 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5230 // initializer-if-any};
5231 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005232 // FIXME. rewriter does not support __block c++ objects which
5233 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005234 if (hasInit)
5235 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5236 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5237 if (CXXDecl && CXXDecl->isDefaultConstructor())
5238 hasInit = false;
5239 }
5240
Fariborz Jahanian11671902012-02-07 17:11:38 +00005241 unsigned flags = 0;
5242 if (HasCopyAndDispose)
5243 flags |= BLOCK_HAS_COPY_DISPOSE;
5244 Name = ND->getNameAsString();
5245 ByrefType.clear();
5246 RewriteByRefString(ByrefType, Name, ND);
5247 std::string ForwardingCastType("(");
5248 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005249 ByrefType += " " + Name + " = {(void*)";
5250 ByrefType += utostr(isa);
5251 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5252 ByrefType += utostr(flags);
5253 ByrefType += ", ";
5254 ByrefType += "sizeof(";
5255 RewriteByRefString(ByrefType, Name, ND);
5256 ByrefType += ")";
5257 if (HasCopyAndDispose) {
5258 ByrefType += ", __Block_byref_id_object_copy_";
5259 ByrefType += utostr(flag);
5260 ByrefType += ", __Block_byref_id_object_dispose_";
5261 ByrefType += utostr(flag);
5262 }
5263
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005264 if (!firstDecl) {
5265 // In multiple __block declarations, and for all but 1st declaration,
5266 // find location of the separating comma. This would be start location
5267 // where new text is to be inserted.
5268 DeclLoc = ND->getLocation();
5269 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5270 const char *commaBuf = startDeclBuf;
5271 while (*commaBuf != ',')
5272 commaBuf--;
5273 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5274 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5275 startBuf = commaBuf;
5276 }
5277
Fariborz Jahanian11671902012-02-07 17:11:38 +00005278 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005279 ByrefType += "};\n";
5280 unsigned nameSize = Name.size();
5281 // for block or function pointer declaration. Name is aleady
5282 // part of the declaration.
5283 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5284 nameSize = 1;
5285 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5286 }
5287 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005288 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005289 SourceLocation startLoc;
5290 Expr *E = ND->getInit();
5291 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5292 startLoc = ECE->getLParenLoc();
5293 else
5294 startLoc = E->getLocStart();
5295 startLoc = SM->getExpansionLoc(startLoc);
5296 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005297 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005298
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005299 const char separator = lastDecl ? ';' : ',';
5300 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5301 const char *separatorBuf = strchr(startInitializerBuf, separator);
5302 assert((*separatorBuf == separator) &&
5303 "RewriteByRefVar: can't find ';' or ','");
5304 SourceLocation separatorLoc =
5305 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5306
5307 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005308 }
5309 return;
5310}
5311
5312void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5313 // Add initializers for any closure decl refs.
5314 GetBlockDeclRefExprs(Exp->getBody());
5315 if (BlockDeclRefs.size()) {
5316 // Unique all "by copy" declarations.
5317 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005318 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005319 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5320 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5321 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5322 }
5323 }
5324 // Unique all "by ref" declarations.
5325 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005326 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005327 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5328 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5329 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5330 }
5331 }
5332 // Find any imported blocks...they will need special attention.
5333 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005334 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005335 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5336 BlockDeclRefs[i]->getType()->isBlockPointerType())
5337 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5338 }
5339}
5340
5341FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5342 IdentifierInfo *ID = &Context->Idents.get(name);
5343 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5344 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5345 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005346 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005347}
5348
5349Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005350 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005351
Fariborz Jahanian11671902012-02-07 17:11:38 +00005352 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005353
Fariborz Jahanian11671902012-02-07 17:11:38 +00005354 Blocks.push_back(Exp);
5355
5356 CollectBlockDeclRefInfo(Exp);
5357
5358 // Add inner imported variables now used in current block.
5359 int countOfInnerDecls = 0;
5360 if (!InnerBlockDeclRefs.empty()) {
5361 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005362 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005363 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005364 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005365 // We need to save the copied-in variables in nested
5366 // blocks because it is needed at the end for some of the API generations.
5367 // See SynthesizeBlockLiterals routine.
5368 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5369 BlockDeclRefs.push_back(Exp);
5370 BlockByCopyDeclsPtrSet.insert(VD);
5371 BlockByCopyDecls.push_back(VD);
5372 }
John McCall113bee02012-03-10 09:33:50 +00005373 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005374 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5375 BlockDeclRefs.push_back(Exp);
5376 BlockByRefDeclsPtrSet.insert(VD);
5377 BlockByRefDecls.push_back(VD);
5378 }
5379 }
5380 // Find any imported blocks...they will need special attention.
5381 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005382 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005383 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5384 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5385 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5386 }
5387 InnerDeclRefsCount.push_back(countOfInnerDecls);
5388
5389 std::string FuncName;
5390
5391 if (CurFunctionDef)
5392 FuncName = CurFunctionDef->getNameAsString();
5393 else if (CurMethodDef)
5394 BuildUniqueMethodName(FuncName, CurMethodDef);
5395 else if (GlobalVarDecl)
5396 FuncName = std::string(GlobalVarDecl->getNameAsString());
5397
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005398 bool GlobalBlockExpr =
5399 block->getDeclContext()->getRedeclContext()->isFileContext();
5400
5401 if (GlobalBlockExpr && !GlobalVarDecl) {
5402 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5403 GlobalBlockExpr = false;
5404 }
5405
Fariborz Jahanian11671902012-02-07 17:11:38 +00005406 std::string BlockNumber = utostr(Blocks.size()-1);
5407
Fariborz Jahanian11671902012-02-07 17:11:38 +00005408 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5409
5410 // Get a pointer to the function type so we can cast appropriately.
5411 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5412 QualType FType = Context->getPointerType(BFT);
5413
5414 FunctionDecl *FD;
5415 Expr *NewRep;
5416
Benjamin Kramer60509af2013-09-09 14:48:42 +00005417 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005418 std::string Tag;
5419
5420 if (GlobalBlockExpr)
5421 Tag = "__global_";
5422 else
5423 Tag = "__";
5424 Tag += FuncName + "_block_impl_" + BlockNumber;
5425
Fariborz Jahanian11671902012-02-07 17:11:38 +00005426 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005427 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005428 SourceLocation());
5429
5430 SmallVector<Expr*, 4> InitExprs;
5431
5432 // Initialize the block function.
5433 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005434 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5435 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005436 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5437 CK_BitCast, Arg);
5438 InitExprs.push_back(castExpr);
5439
5440 // Initialize the block descriptor.
5441 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5442
5443 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5444 SourceLocation(), SourceLocation(),
5445 &Context->Idents.get(DescData.c_str()),
5446 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005447 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005448 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005449 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005450 Context->VoidPtrTy,
5451 VK_LValue,
5452 SourceLocation()),
5453 UO_AddrOf,
5454 Context->getPointerType(Context->VoidPtrTy),
5455 VK_RValue, OK_Ordinary,
5456 SourceLocation());
5457 InitExprs.push_back(DescRefExpr);
5458
5459 // Add initializers for any closure decl refs.
5460 if (BlockDeclRefs.size()) {
5461 Expr *Exp;
5462 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005463 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005464 E = BlockByCopyDecls.end(); I != E; ++I) {
5465 if (isObjCType((*I)->getType())) {
5466 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5467 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005468 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5469 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005470 if (HasLocalVariableExternalStorage(*I)) {
5471 QualType QT = (*I)->getType();
5472 QT = Context->getPointerType(QT);
5473 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5474 OK_Ordinary, SourceLocation());
5475 }
5476 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5477 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005478 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5479 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005480 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5481 CK_BitCast, Arg);
5482 } else {
5483 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005484 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5485 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005486 if (HasLocalVariableExternalStorage(*I)) {
5487 QualType QT = (*I)->getType();
5488 QT = Context->getPointerType(QT);
5489 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5490 OK_Ordinary, SourceLocation());
5491 }
5492
5493 }
5494 InitExprs.push_back(Exp);
5495 }
5496 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005497 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005498 E = BlockByRefDecls.end(); I != E; ++I) {
5499 ValueDecl *ND = (*I);
5500 std::string Name(ND->getNameAsString());
5501 std::string RecName;
5502 RewriteByRefString(RecName, Name, ND, true);
5503 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5504 + sizeof("struct"));
5505 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5506 SourceLocation(), SourceLocation(),
5507 II);
5508 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5509 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5510
5511 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005512 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005513 SourceLocation());
5514 bool isNestedCapturedVar = false;
5515 if (block)
5516 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5517 ce = block->capture_end(); ci != ce; ++ci) {
5518 const VarDecl *variable = ci->getVariable();
5519 if (variable == ND && ci->isNested()) {
5520 assert (ci->isByRef() &&
5521 "SynthBlockInitExpr - captured block variable is not byref");
5522 isNestedCapturedVar = true;
5523 break;
5524 }
5525 }
5526 // captured nested byref variable has its address passed. Do not take
5527 // its address again.
5528 if (!isNestedCapturedVar)
5529 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5530 Context->getPointerType(Exp->getType()),
5531 VK_RValue, OK_Ordinary, SourceLocation());
5532 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5533 InitExprs.push_back(Exp);
5534 }
5535 }
5536 if (ImportedBlockDecls.size()) {
5537 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5538 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5539 unsigned IntSize =
5540 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5541 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5542 Context->IntTy, SourceLocation());
5543 InitExprs.push_back(FlagExp);
5544 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005545 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005546 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005547
5548 if (GlobalBlockExpr) {
5549 assert (GlobalConstructionExp == 0 &&
5550 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5551 GlobalConstructionExp = NewRep;
5552 NewRep = DRE;
5553 }
5554
Fariborz Jahanian11671902012-02-07 17:11:38 +00005555 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5556 Context->getPointerType(NewRep->getType()),
5557 VK_RValue, OK_Ordinary, SourceLocation());
5558 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5559 NewRep);
5560 BlockDeclRefs.clear();
5561 BlockByRefDecls.clear();
5562 BlockByRefDeclsPtrSet.clear();
5563 BlockByCopyDecls.clear();
5564 BlockByCopyDeclsPtrSet.clear();
5565 ImportedBlockDecls.clear();
5566 return NewRep;
5567}
5568
5569bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5570 if (const ObjCForCollectionStmt * CS =
5571 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5572 return CS->getElement() == DS;
5573 return false;
5574}
5575
5576//===----------------------------------------------------------------------===//
5577// Function Body / Expression rewriting
5578//===----------------------------------------------------------------------===//
5579
5580Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5581 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5582 isa<DoStmt>(S) || isa<ForStmt>(S))
5583 Stmts.push_back(S);
5584 else if (isa<ObjCForCollectionStmt>(S)) {
5585 Stmts.push_back(S);
5586 ObjCBcLabelNo.push_back(++BcLabelCount);
5587 }
5588
5589 // Pseudo-object operations and ivar references need special
5590 // treatment because we're going to recursively rewrite them.
5591 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5592 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5593 return RewritePropertyOrImplicitSetter(PseudoOp);
5594 } else {
5595 return RewritePropertyOrImplicitGetter(PseudoOp);
5596 }
5597 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5598 return RewriteObjCIvarRefExpr(IvarRefExpr);
5599 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005600 else if (isa<OpaqueValueExpr>(S))
5601 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005602
5603 SourceRange OrigStmtRange = S->getSourceRange();
5604
5605 // Perform a bottom up rewrite of all children.
5606 for (Stmt::child_range CI = S->children(); CI; ++CI)
5607 if (*CI) {
5608 Stmt *childStmt = (*CI);
5609 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5610 if (newStmt) {
5611 *CI = newStmt;
5612 }
5613 }
5614
5615 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005616 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005617 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5618 InnerContexts.insert(BE->getBlockDecl());
5619 ImportedLocalExternalDecls.clear();
5620 GetInnerBlockDeclRefExprs(BE->getBody(),
5621 InnerBlockDeclRefs, InnerContexts);
5622 // Rewrite the block body in place.
5623 Stmt *SaveCurrentBody = CurrentBody;
5624 CurrentBody = BE->getBody();
5625 PropParentMap = 0;
5626 // block literal on rhs of a property-dot-sytax assignment
5627 // must be replaced by its synthesize ast so getRewrittenText
5628 // works as expected. In this case, what actually ends up on RHS
5629 // is the blockTranscribed which is the helper function for the
5630 // block literal; as in: self.c = ^() {[ace ARR];};
5631 bool saveDisableReplaceStmt = DisableReplaceStmt;
5632 DisableReplaceStmt = false;
5633 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5634 DisableReplaceStmt = saveDisableReplaceStmt;
5635 CurrentBody = SaveCurrentBody;
5636 PropParentMap = 0;
5637 ImportedLocalExternalDecls.clear();
5638 // Now we snarf the rewritten text and stash it away for later use.
5639 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5640 RewrittenBlockExprs[BE] = Str;
5641
5642 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5643
5644 //blockTranscribed->dump();
5645 ReplaceStmt(S, blockTranscribed);
5646 return blockTranscribed;
5647 }
5648 // Handle specific things.
5649 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5650 return RewriteAtEncode(AtEncode);
5651
5652 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5653 return RewriteAtSelector(AtSelector);
5654
5655 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5656 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005657
5658 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5659 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005660
Patrick Beard0caa3942012-04-19 00:25:12 +00005661 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5662 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005663
5664 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5665 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005666
5667 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5668 dyn_cast<ObjCDictionaryLiteral>(S))
5669 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005670
5671 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5672#if 0
5673 // Before we rewrite it, put the original message expression in a comment.
5674 SourceLocation startLoc = MessExpr->getLocStart();
5675 SourceLocation endLoc = MessExpr->getLocEnd();
5676
5677 const char *startBuf = SM->getCharacterData(startLoc);
5678 const char *endBuf = SM->getCharacterData(endLoc);
5679
5680 std::string messString;
5681 messString += "// ";
5682 messString.append(startBuf, endBuf-startBuf+1);
5683 messString += "\n";
5684
5685 // FIXME: Missing definition of
5686 // InsertText(clang::SourceLocation, char const*, unsigned int).
5687 // InsertText(startLoc, messString.c_str(), messString.size());
5688 // Tried this, but it didn't work either...
5689 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5690#endif
5691 return RewriteMessageExpr(MessExpr);
5692 }
5693
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005694 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5695 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5696 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5697 }
5698
Fariborz Jahanian11671902012-02-07 17:11:38 +00005699 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5700 return RewriteObjCTryStmt(StmtTry);
5701
5702 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5703 return RewriteObjCSynchronizedStmt(StmtTry);
5704
5705 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5706 return RewriteObjCThrowStmt(StmtThrow);
5707
5708 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5709 return RewriteObjCProtocolExpr(ProtocolExp);
5710
5711 if (ObjCForCollectionStmt *StmtForCollection =
5712 dyn_cast<ObjCForCollectionStmt>(S))
5713 return RewriteObjCForCollectionStmt(StmtForCollection,
5714 OrigStmtRange.getEnd());
5715 if (BreakStmt *StmtBreakStmt =
5716 dyn_cast<BreakStmt>(S))
5717 return RewriteBreakStmt(StmtBreakStmt);
5718 if (ContinueStmt *StmtContinueStmt =
5719 dyn_cast<ContinueStmt>(S))
5720 return RewriteContinueStmt(StmtContinueStmt);
5721
5722 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5723 // and cast exprs.
5724 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5725 // FIXME: What we're doing here is modifying the type-specifier that
5726 // precedes the first Decl. In the future the DeclGroup should have
5727 // a separate type-specifier that we can rewrite.
5728 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5729 // the context of an ObjCForCollectionStmt. For example:
5730 // NSArray *someArray;
5731 // for (id <FooProtocol> index in someArray) ;
5732 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5733 // and it depends on the original text locations/positions.
5734 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5735 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5736
5737 // Blocks rewrite rules.
5738 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5739 DI != DE; ++DI) {
5740 Decl *SD = *DI;
5741 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5742 if (isTopLevelBlockPointerType(ND->getType()))
5743 RewriteBlockPointerDecl(ND);
5744 else if (ND->getType()->isFunctionPointerType())
5745 CheckFunctionPointerDecl(ND->getType(), ND);
5746 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5747 if (VD->hasAttr<BlocksAttr>()) {
5748 static unsigned uniqueByrefDeclCount = 0;
5749 assert(!BlockByRefDeclNo.count(ND) &&
5750 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5751 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005752 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005753 }
5754 else
5755 RewriteTypeOfDecl(VD);
5756 }
5757 }
5758 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5759 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5760 RewriteBlockPointerDecl(TD);
5761 else if (TD->getUnderlyingType()->isFunctionPointerType())
5762 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5763 }
5764 }
5765 }
5766
5767 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5768 RewriteObjCQualifiedInterfaceTypes(CE);
5769
5770 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5771 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5772 assert(!Stmts.empty() && "Statement stack is empty");
5773 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5774 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5775 && "Statement stack mismatch");
5776 Stmts.pop_back();
5777 }
5778 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005779 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5780 ValueDecl *VD = DRE->getDecl();
5781 if (VD->hasAttr<BlocksAttr>())
5782 return RewriteBlockDeclRefExpr(DRE);
5783 if (HasLocalVariableExternalStorage(VD))
5784 return RewriteLocalVariableExternalStorage(DRE);
5785 }
5786
5787 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5788 if (CE->getCallee()->getType()->isBlockPointerType()) {
5789 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5790 ReplaceStmt(S, BlockCall);
5791 return BlockCall;
5792 }
5793 }
5794 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5795 RewriteCastExpr(CE);
5796 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005797 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5798 RewriteImplicitCastObjCExpr(ICE);
5799 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005800#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005801
Fariborz Jahanian11671902012-02-07 17:11:38 +00005802 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5803 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5804 ICE->getSubExpr(),
5805 SourceLocation());
5806 // Get the new text.
5807 std::string SStr;
5808 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005809 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005810 const std::string &Str = Buf.str();
5811
5812 printf("CAST = %s\n", &Str[0]);
5813 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5814 delete S;
5815 return Replacement;
5816 }
5817#endif
5818 // Return this stmt unmodified.
5819 return S;
5820}
5821
5822void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005823 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005824 if (isTopLevelBlockPointerType(FD->getType()))
5825 RewriteBlockPointerDecl(FD);
5826 if (FD->getType()->isObjCQualifiedIdType() ||
5827 FD->getType()->isObjCQualifiedInterfaceType())
5828 RewriteObjCQualifiedInterfaceTypes(FD);
5829 }
5830}
5831
5832/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5833/// main file of the input.
5834void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5835 switch (D->getKind()) {
5836 case Decl::Function: {
5837 FunctionDecl *FD = cast<FunctionDecl>(D);
5838 if (FD->isOverloadedOperator())
5839 return;
5840
5841 // Since function prototypes don't have ParmDecl's, we check the function
5842 // prototype. This enables us to rewrite function declarations and
5843 // definitions using the same code.
5844 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5845
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005846 if (!FD->isThisDeclarationADefinition())
5847 break;
5848
Fariborz Jahanian11671902012-02-07 17:11:38 +00005849 // FIXME: If this should support Obj-C++, support CXXTryStmt
5850 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5851 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005852 CurrentBody = Body;
5853 Body =
5854 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5855 FD->setBody(Body);
5856 CurrentBody = 0;
5857 if (PropParentMap) {
5858 delete PropParentMap;
5859 PropParentMap = 0;
5860 }
5861 // This synthesizes and inserts the block "impl" struct, invoke function,
5862 // and any copy/dispose helper functions.
5863 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005864 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005865 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005866 }
5867 break;
5868 }
5869 case Decl::ObjCMethod: {
5870 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5871 if (CompoundStmt *Body = MD->getCompoundBody()) {
5872 CurMethodDef = MD;
5873 CurrentBody = Body;
5874 Body =
5875 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5876 MD->setBody(Body);
5877 CurrentBody = 0;
5878 if (PropParentMap) {
5879 delete PropParentMap;
5880 PropParentMap = 0;
5881 }
5882 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005883 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005884 CurMethodDef = 0;
5885 }
5886 break;
5887 }
5888 case Decl::ObjCImplementation: {
5889 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5890 ClassImplementation.push_back(CI);
5891 break;
5892 }
5893 case Decl::ObjCCategoryImpl: {
5894 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5895 CategoryImplementation.push_back(CI);
5896 break;
5897 }
5898 case Decl::Var: {
5899 VarDecl *VD = cast<VarDecl>(D);
5900 RewriteObjCQualifiedInterfaceTypes(VD);
5901 if (isTopLevelBlockPointerType(VD->getType()))
5902 RewriteBlockPointerDecl(VD);
5903 else if (VD->getType()->isFunctionPointerType()) {
5904 CheckFunctionPointerDecl(VD->getType(), VD);
5905 if (VD->getInit()) {
5906 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5907 RewriteCastExpr(CE);
5908 }
5909 }
5910 } else if (VD->getType()->isRecordType()) {
5911 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5912 if (RD->isCompleteDefinition())
5913 RewriteRecordBody(RD);
5914 }
5915 if (VD->getInit()) {
5916 GlobalVarDecl = VD;
5917 CurrentBody = VD->getInit();
5918 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5919 CurrentBody = 0;
5920 if (PropParentMap) {
5921 delete PropParentMap;
5922 PropParentMap = 0;
5923 }
5924 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5925 GlobalVarDecl = 0;
5926
5927 // This is needed for blocks.
5928 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5929 RewriteCastExpr(CE);
5930 }
5931 }
5932 break;
5933 }
5934 case Decl::TypeAlias:
5935 case Decl::Typedef: {
5936 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5937 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5938 RewriteBlockPointerDecl(TD);
5939 else if (TD->getUnderlyingType()->isFunctionPointerType())
5940 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005941 else
5942 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005943 }
5944 break;
5945 }
5946 case Decl::CXXRecord:
5947 case Decl::Record: {
5948 RecordDecl *RD = cast<RecordDecl>(D);
5949 if (RD->isCompleteDefinition())
5950 RewriteRecordBody(RD);
5951 break;
5952 }
5953 default:
5954 break;
5955 }
5956 // Nothing yet.
5957}
5958
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005959/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5960/// protocol reference symbols in the for of:
5961/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5962static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5963 ObjCProtocolDecl *PDecl,
5964 std::string &Result) {
5965 // Also output .objc_protorefs$B section and its meta-data.
5966 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005967 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005968 Result += "struct _protocol_t *";
5969 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5970 Result += PDecl->getNameAsString();
5971 Result += " = &";
5972 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5973 Result += ";\n";
5974}
5975
Fariborz Jahanian11671902012-02-07 17:11:38 +00005976void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5977 if (Diags.hasErrorOccurred())
5978 return;
5979
5980 RewriteInclude();
5981
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005982 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005983 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005984 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005985 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005986 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5987 HandleTopLevelSingleDecl(FDecl);
5988 }
5989
Fariborz Jahanian11671902012-02-07 17:11:38 +00005990 // Here's a great place to add any extra declarations that may be needed.
5991 // Write out meta data for each @protocol(<expr>).
5992 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005993 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00005994 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005995 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5996 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005997
5998 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005999
6000 if (ClassImplementation.size() || CategoryImplementation.size())
6001 RewriteImplementations();
6002
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00006003 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6004 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6005 // Write struct declaration for the class matching its ivar declarations.
6006 // Note that for modern abi, this is postponed until the end of TU
6007 // because class extensions and the implementation might declare their own
6008 // private ivars.
6009 RewriteInterfaceDecl(CDecl);
6010 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006011
Fariborz Jahanian11671902012-02-07 17:11:38 +00006012 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6013 // we are done.
6014 if (const RewriteBuffer *RewriteBuf =
6015 Rewrite.getRewriteBufferFor(MainFileID)) {
6016 //printf("Changed:\n");
6017 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6018 } else {
6019 llvm::errs() << "No changes\n";
6020 }
6021
6022 if (ClassImplementation.size() || CategoryImplementation.size() ||
6023 ProtocolExprDecls.size()) {
6024 // Rewrite Objective-c meta data*
6025 std::string ResultStr;
6026 RewriteMetaDataIntoBuffer(ResultStr);
6027 // Emit metadata.
6028 *OutFile << ResultStr;
6029 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006030 // Emit ImageInfo;
6031 {
6032 std::string ResultStr;
6033 WriteImageInfo(ResultStr);
6034 *OutFile << ResultStr;
6035 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006036 OutFile->flush();
6037}
6038
6039void RewriteModernObjC::Initialize(ASTContext &context) {
6040 InitializeCommon(context);
6041
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006042 Preamble += "#ifndef __OBJC2__\n";
6043 Preamble += "#define __OBJC2__\n";
6044 Preamble += "#endif\n";
6045
Fariborz Jahanian11671902012-02-07 17:11:38 +00006046 // declaring objc_selector outside the parameter list removes a silly
6047 // scope related warning...
6048 if (IsHeader)
6049 Preamble = "#pragma once\n";
6050 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006051 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6052 Preamble += "\n\tstruct objc_object *superClass; ";
6053 // Add a constructor for creating temporary objects.
6054 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6055 Preamble += ": object(o), superClass(s) {} ";
6056 Preamble += "\n};\n";
6057
Fariborz Jahanian11671902012-02-07 17:11:38 +00006058 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006059 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006060 // These are currently generated.
6061 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006062 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006063 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006064 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6065 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006066 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006067 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006068 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6069 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006070 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006071
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006072 // These need be generated for performance. Currently they are not,
6073 // using API calls instead.
6074 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6075 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6076 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6077
Fariborz Jahanian11671902012-02-07 17:11:38 +00006078 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006079 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6080 Preamble += "typedef struct objc_object Protocol;\n";
6081 Preamble += "#define _REWRITER_typedef_Protocol\n";
6082 Preamble += "#endif\n";
6083 if (LangOpts.MicrosoftExt) {
6084 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6085 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006086 }
6087 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006088 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006089
6090 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6091 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6092 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6093 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6094 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6095
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006096 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006097 Preamble += "(const char *);\n";
6098 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6099 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006100 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006101 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006102 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006103 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006104 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6105 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006106 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006107 Preamble += "#ifdef _WIN64\n";
6108 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6109 Preamble += "#else\n";
6110 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6111 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006112 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6113 Preamble += "struct __objcFastEnumerationState {\n\t";
6114 Preamble += "unsigned long state;\n\t";
6115 Preamble += "void **itemsPtr;\n\t";
6116 Preamble += "unsigned long *mutationsPtr;\n\t";
6117 Preamble += "unsigned long extra[5];\n};\n";
6118 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6119 Preamble += "#define __FASTENUMERATIONSTATE\n";
6120 Preamble += "#endif\n";
6121 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6122 Preamble += "struct __NSConstantStringImpl {\n";
6123 Preamble += " int *isa;\n";
6124 Preamble += " int flags;\n";
6125 Preamble += " char *str;\n";
6126 Preamble += " long length;\n";
6127 Preamble += "};\n";
6128 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6129 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6130 Preamble += "#else\n";
6131 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6132 Preamble += "#endif\n";
6133 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6134 Preamble += "#endif\n";
6135 // Blocks preamble.
6136 Preamble += "#ifndef BLOCK_IMPL\n";
6137 Preamble += "#define BLOCK_IMPL\n";
6138 Preamble += "struct __block_impl {\n";
6139 Preamble += " void *isa;\n";
6140 Preamble += " int Flags;\n";
6141 Preamble += " int Reserved;\n";
6142 Preamble += " void *FuncPtr;\n";
6143 Preamble += "};\n";
6144 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6145 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6146 Preamble += "extern \"C\" __declspec(dllexport) "
6147 "void _Block_object_assign(void *, const void *, const int);\n";
6148 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6149 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6150 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6151 Preamble += "#else\n";
6152 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6153 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6154 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6155 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6156 Preamble += "#endif\n";
6157 Preamble += "#endif\n";
6158 if (LangOpts.MicrosoftExt) {
6159 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6160 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6161 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6162 Preamble += "#define __attribute__(X)\n";
6163 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006164 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006165 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006166 Preamble += "#endif\n";
6167 Preamble += "#ifndef __block\n";
6168 Preamble += "#define __block\n";
6169 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006170 }
6171 else {
6172 Preamble += "#define __block\n";
6173 Preamble += "#define __weak\n";
6174 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006175
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006176 // Declarations required for modern objective-c array and dictionary literals.
6177 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006178 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006179 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006180 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006181 Preamble += "\tva_list marker;\n";
6182 Preamble += "\tva_start(marker, count);\n";
6183 Preamble += "\tarr = new void *[count];\n";
6184 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6185 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6186 Preamble += "\tva_end( marker );\n";
6187 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006188 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006189 Preamble += "\tdelete[] arr;\n";
6190 Preamble += " }\n";
6191 Preamble += "};\n";
6192
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006193 // Declaration required for implementation of @autoreleasepool statement.
6194 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6195 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6196 Preamble += "struct __AtAutoreleasePool {\n";
6197 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6198 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6199 Preamble += " void * atautoreleasepoolobj;\n";
6200 Preamble += "};\n";
6201
Fariborz Jahanian11671902012-02-07 17:11:38 +00006202 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6203 // as this avoids warning in any 64bit/32bit compilation model.
6204 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6205}
6206
6207/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6208/// ivar offset.
6209void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6210 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006211 Result += "__OFFSETOFIVAR__(struct ";
6212 Result += ivar->getContainingInterface()->getNameAsString();
6213 if (LangOpts.MicrosoftExt)
6214 Result += "_IMPL";
6215 Result += ", ";
6216 if (ivar->isBitField())
6217 ObjCIvarBitfieldGroupDecl(ivar, Result);
6218 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006219 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006220 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006221}
6222
6223/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6224/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006225/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006226/// char *attributes;
6227/// }
6228
6229/// struct _prop_list_t {
6230/// uint32_t entsize; // sizeof(struct _prop_t)
6231/// uint32_t count_of_properties;
6232/// struct _prop_t prop_list[count_of_properties];
6233/// }
6234
6235/// struct _protocol_t;
6236
6237/// struct _protocol_list_t {
6238/// long protocol_count; // Note, this is 32/64 bit
6239/// struct _protocol_t * protocol_list[protocol_count];
6240/// }
6241
6242/// struct _objc_method {
6243/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006244/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006245/// char *_imp;
6246/// }
6247
6248/// struct _method_list_t {
6249/// uint32_t entsize; // sizeof(struct _objc_method)
6250/// uint32_t method_count;
6251/// struct _objc_method method_list[method_count];
6252/// }
6253
6254/// struct _protocol_t {
6255/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006256/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006257/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006258/// const struct method_list_t *instance_methods;
6259/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006260/// const struct method_list_t *optionalInstanceMethods;
6261/// const struct method_list_t *optionalClassMethods;
6262/// const struct _prop_list_t * properties;
6263/// const uint32_t size; // sizeof(struct _protocol_t)
6264/// const uint32_t flags; // = 0
6265/// const char ** extendedMethodTypes;
6266/// }
6267
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006268/// struct _ivar_t {
6269/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006270/// const char *name;
6271/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006272/// uint32_t alignment;
6273/// uint32_t size;
6274/// }
6275
6276/// struct _ivar_list_t {
6277/// uint32 entsize; // sizeof(struct _ivar_t)
6278/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006279/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006280/// }
6281
6282/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006283/// uint32_t flags;
6284/// uint32_t instanceStart;
6285/// uint32_t instanceSize;
6286/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006287/// const uint8_t *ivarLayout;
6288/// const char *name;
6289/// const struct _method_list_t *baseMethods;
6290/// const struct _protocol_list_t *baseProtocols;
6291/// const struct _ivar_list_t *ivars;
6292/// const uint8_t *weakIvarLayout;
6293/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006294/// }
6295
6296/// struct _class_t {
6297/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006298/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006299/// void *cache;
6300/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006301/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006302/// }
6303
6304/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006305/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006306/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006307/// const struct _method_list_t *instance_methods;
6308/// const struct _method_list_t *class_methods;
6309/// const struct _protocol_list_t *protocols;
6310/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006311/// }
6312
6313/// MessageRefTy - LLVM for:
6314/// struct _message_ref_t {
6315/// IMP messenger;
6316/// SEL name;
6317/// };
6318
6319/// SuperMessageRefTy - LLVM for:
6320/// struct _super_message_ref_t {
6321/// SUPER_IMP messenger;
6322/// SEL name;
6323/// };
6324
Fariborz Jahanian45489622012-03-14 18:09:23 +00006325static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006326 static bool meta_data_declared = false;
6327 if (meta_data_declared)
6328 return;
6329
6330 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006331 Result += "\tconst char *name;\n";
6332 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006333 Result += "};\n";
6334
6335 Result += "\nstruct _protocol_t;\n";
6336
Fariborz Jahanian11671902012-02-07 17:11:38 +00006337 Result += "\nstruct _objc_method {\n";
6338 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006339 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006340 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006341 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006342
6343 Result += "\nstruct _protocol_t {\n";
6344 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006345 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006346 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006347 Result += "\tconst struct method_list_t *instance_methods;\n";
6348 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006349 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6350 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6351 Result += "\tconst struct _prop_list_t * properties;\n";
6352 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6353 Result += "\tconst unsigned int flags; // = 0\n";
6354 Result += "\tconst char ** extendedMethodTypes;\n";
6355 Result += "};\n";
6356
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006357 Result += "\nstruct _ivar_t {\n";
6358 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006359 Result += "\tconst char *name;\n";
6360 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006361 Result += "\tunsigned int alignment;\n";
6362 Result += "\tunsigned int size;\n";
6363 Result += "};\n";
6364
6365 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006366 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006367 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006368 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006369 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6370 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006371 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006372 Result += "\tconst unsigned char *ivarLayout;\n";
6373 Result += "\tconst char *name;\n";
6374 Result += "\tconst struct _method_list_t *baseMethods;\n";
6375 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6376 Result += "\tconst struct _ivar_list_t *ivars;\n";
6377 Result += "\tconst unsigned char *weakIvarLayout;\n";
6378 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006379 Result += "};\n";
6380
6381 Result += "\nstruct _class_t {\n";
6382 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006383 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006384 Result += "\tvoid *cache;\n";
6385 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006386 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006387 Result += "};\n";
6388
6389 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006390 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006391 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006392 Result += "\tconst struct _method_list_t *instance_methods;\n";
6393 Result += "\tconst struct _method_list_t *class_methods;\n";
6394 Result += "\tconst struct _protocol_list_t *protocols;\n";
6395 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006396 Result += "};\n";
6397
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006398 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006399 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006400 meta_data_declared = true;
6401}
6402
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006403static void Write_protocol_list_t_TypeDecl(std::string &Result,
6404 long super_protocol_count) {
6405 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6406 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6407 Result += "\tstruct _protocol_t *super_protocols[";
6408 Result += utostr(super_protocol_count); Result += "];\n";
6409 Result += "}";
6410}
6411
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006412static void Write_method_list_t_TypeDecl(std::string &Result,
6413 unsigned int method_count) {
6414 Result += "struct /*_method_list_t*/"; Result += " {\n";
6415 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6416 Result += "\tunsigned int method_count;\n";
6417 Result += "\tstruct _objc_method method_list[";
6418 Result += utostr(method_count); Result += "];\n";
6419 Result += "}";
6420}
6421
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006422static void Write__prop_list_t_TypeDecl(std::string &Result,
6423 unsigned int property_count) {
6424 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6425 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6426 Result += "\tunsigned int count_of_properties;\n";
6427 Result += "\tstruct _prop_t prop_list[";
6428 Result += utostr(property_count); Result += "];\n";
6429 Result += "}";
6430}
6431
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006432static void Write__ivar_list_t_TypeDecl(std::string &Result,
6433 unsigned int ivar_count) {
6434 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6435 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6436 Result += "\tunsigned int count;\n";
6437 Result += "\tstruct _ivar_t ivar_list[";
6438 Result += utostr(ivar_count); Result += "];\n";
6439 Result += "}";
6440}
6441
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006442static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6443 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6444 StringRef VarName,
6445 StringRef ProtocolName) {
6446 if (SuperProtocols.size() > 0) {
6447 Result += "\nstatic ";
6448 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6449 Result += " "; Result += VarName;
6450 Result += ProtocolName;
6451 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6452 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6453 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6454 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6455 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6456 Result += SuperPD->getNameAsString();
6457 if (i == e-1)
6458 Result += "\n};\n";
6459 else
6460 Result += ",\n";
6461 }
6462 }
6463}
6464
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006465static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6466 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006467 ArrayRef<ObjCMethodDecl *> Methods,
6468 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006469 StringRef TopLevelDeclName,
6470 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006471 if (Methods.size() > 0) {
6472 Result += "\nstatic ";
6473 Write_method_list_t_TypeDecl(Result, Methods.size());
6474 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006475 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006476 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6477 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6478 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6479 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6480 ObjCMethodDecl *MD = Methods[i];
6481 if (i == 0)
6482 Result += "\t{{(struct objc_selector *)\"";
6483 else
6484 Result += "\t{(struct objc_selector *)\"";
6485 Result += (MD)->getSelector().getAsString(); Result += "\"";
6486 Result += ", ";
6487 std::string MethodTypeString;
6488 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6489 Result += "\""; Result += MethodTypeString; Result += "\"";
6490 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006491 if (!MethodImpl)
6492 Result += "0";
6493 else {
6494 Result += "(void *)";
6495 Result += RewriteObj.MethodInternalNames[MD];
6496 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006497 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006498 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006499 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006500 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006501 }
6502 Result += "};\n";
6503 }
6504}
6505
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006506static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006507 ASTContext *Context, std::string &Result,
6508 ArrayRef<ObjCPropertyDecl *> Properties,
6509 const Decl *Container,
6510 StringRef VarName,
6511 StringRef ProtocolName) {
6512 if (Properties.size() > 0) {
6513 Result += "\nstatic ";
6514 Write__prop_list_t_TypeDecl(Result, Properties.size());
6515 Result += " "; Result += VarName;
6516 Result += ProtocolName;
6517 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6518 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6519 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6520 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6521 ObjCPropertyDecl *PropDecl = Properties[i];
6522 if (i == 0)
6523 Result += "\t{{\"";
6524 else
6525 Result += "\t{\"";
6526 Result += PropDecl->getName(); Result += "\",";
6527 std::string PropertyTypeString, QuotePropertyTypeString;
6528 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6529 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6530 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6531 if (i == e-1)
6532 Result += "}}\n";
6533 else
6534 Result += "},\n";
6535 }
6536 Result += "};\n";
6537 }
6538}
6539
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006540// Metadata flags
6541enum MetaDataDlags {
6542 CLS = 0x0,
6543 CLS_META = 0x1,
6544 CLS_ROOT = 0x2,
6545 OBJC2_CLS_HIDDEN = 0x10,
6546 CLS_EXCEPTION = 0x20,
6547
6548 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6549 CLS_HAS_IVAR_RELEASER = 0x40,
6550 /// class was compiled with -fobjc-arr
6551 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6552};
6553
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006554static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6555 unsigned int flags,
6556 const std::string &InstanceStart,
6557 const std::string &InstanceSize,
6558 ArrayRef<ObjCMethodDecl *>baseMethods,
6559 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6560 ArrayRef<ObjCIvarDecl *>ivars,
6561 ArrayRef<ObjCPropertyDecl *>Properties,
6562 StringRef VarName,
6563 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006564 Result += "\nstatic struct _class_ro_t ";
6565 Result += VarName; Result += ClassName;
6566 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6567 Result += "\t";
6568 Result += llvm::utostr(flags); Result += ", ";
6569 Result += InstanceStart; Result += ", ";
6570 Result += InstanceSize; Result += ", \n";
6571 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006572 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6573 if (Triple.getArch() == llvm::Triple::x86_64)
6574 // uint32_t const reserved; // only when building for 64bit targets
6575 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006576 // const uint8_t * const ivarLayout;
6577 Result += "0, \n\t";
6578 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006579 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006580 if (baseMethods.size() > 0) {
6581 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006582 if (metaclass)
6583 Result += "_OBJC_$_CLASS_METHODS_";
6584 else
6585 Result += "_OBJC_$_INSTANCE_METHODS_";
6586 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006587 Result += ",\n\t";
6588 }
6589 else
6590 Result += "0, \n\t";
6591
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006592 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006593 Result += "(const struct _objc_protocol_list *)&";
6594 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6595 Result += ",\n\t";
6596 }
6597 else
6598 Result += "0, \n\t";
6599
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006600 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006601 Result += "(const struct _ivar_list_t *)&";
6602 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6603 Result += ",\n\t";
6604 }
6605 else
6606 Result += "0, \n\t";
6607
6608 // weakIvarLayout
6609 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006610 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006611 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006612 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006613 Result += ",\n";
6614 }
6615 else
6616 Result += "0, \n";
6617
6618 Result += "};\n";
6619}
6620
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006621static void Write_class_t(ASTContext *Context, std::string &Result,
6622 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006623 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6624 bool rootClass = (!CDecl->getSuperClass());
6625 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006626
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006627 if (!rootClass) {
6628 // Find the Root class
6629 RootClass = CDecl->getSuperClass();
6630 while (RootClass->getSuperClass()) {
6631 RootClass = RootClass->getSuperClass();
6632 }
6633 }
6634
6635 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006636 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006637 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006638 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006639 if (CDecl->getImplementation())
6640 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006641 else
6642 Result += "__declspec(dllimport) ";
6643
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006644 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006645 Result += CDecl->getNameAsString();
6646 Result += ";\n";
6647 }
6648 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006649 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006650 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006651 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006652 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006653 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006654 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006655 else
6656 Result += "__declspec(dllimport) ";
6657
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006658 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006659 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006660 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006661 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006662
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006663 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006664 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006665 if (RootClass->getImplementation())
6666 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006667 else
6668 Result += "__declspec(dllimport) ";
6669
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006670 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006671 Result += VarName;
6672 Result += RootClass->getNameAsString();
6673 Result += ";\n";
6674 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006675 }
6676
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006677 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6678 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006679 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6680 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006681 if (metaclass) {
6682 if (!rootClass) {
6683 Result += "0, // &"; Result += VarName;
6684 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006685 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006686 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006687 Result += CDecl->getSuperClass()->getNameAsString();
6688 Result += ",\n\t";
6689 }
6690 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006691 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006692 Result += CDecl->getNameAsString();
6693 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006694 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006695 Result += ",\n\t";
6696 }
6697 }
6698 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006699 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006700 Result += CDecl->getNameAsString();
6701 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006702 if (!rootClass) {
6703 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006704 Result += CDecl->getSuperClass()->getNameAsString();
6705 Result += ",\n\t";
6706 }
6707 else
6708 Result += "0,\n\t";
6709 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006710 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6711 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6712 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006713 Result += "&_OBJC_METACLASS_RO_$_";
6714 else
6715 Result += "&_OBJC_CLASS_RO_$_";
6716 Result += CDecl->getNameAsString();
6717 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006718
6719 // Add static function to initialize some of the meta-data fields.
6720 // avoid doing it twice.
6721 if (metaclass)
6722 return;
6723
6724 const ObjCInterfaceDecl *SuperClass =
6725 rootClass ? CDecl : CDecl->getSuperClass();
6726
6727 Result += "static void OBJC_CLASS_SETUP_$_";
6728 Result += CDecl->getNameAsString();
6729 Result += "(void ) {\n";
6730 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6731 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006732 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006733
6734 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006735 Result += ".superclass = ";
6736 if (rootClass)
6737 Result += "&OBJC_CLASS_$_";
6738 else
6739 Result += "&OBJC_METACLASS_$_";
6740
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006741 Result += SuperClass->getNameAsString(); Result += ";\n";
6742
6743 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6744 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6745
6746 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6747 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6748 Result += CDecl->getNameAsString(); Result += ";\n";
6749
6750 if (!rootClass) {
6751 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6752 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6753 Result += SuperClass->getNameAsString(); Result += ";\n";
6754 }
6755
6756 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6757 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6758 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006759}
6760
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006761static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6762 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006763 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006764 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006765 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6766 ArrayRef<ObjCMethodDecl *> ClassMethods,
6767 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6768 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006769 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006770 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006771 // must declare an extern class object in case this class is not implemented
6772 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006773 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006774 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006775 if (ClassDecl->getImplementation())
6776 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006777 else
6778 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006779
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006780 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006781 Result += "OBJC_CLASS_$_"; Result += ClassName;
6782 Result += ";\n";
6783
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006784 Result += "\nstatic struct _category_t ";
6785 Result += "_OBJC_$_CATEGORY_";
6786 Result += ClassName; Result += "_$_"; Result += CatName;
6787 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6788 Result += "{\n";
6789 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006790 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006791 Result += ",\n";
6792 if (InstanceMethods.size() > 0) {
6793 Result += "\t(const struct _method_list_t *)&";
6794 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6795 Result += ClassName; Result += "_$_"; Result += CatName;
6796 Result += ",\n";
6797 }
6798 else
6799 Result += "\t0,\n";
6800
6801 if (ClassMethods.size() > 0) {
6802 Result += "\t(const struct _method_list_t *)&";
6803 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6804 Result += ClassName; Result += "_$_"; Result += CatName;
6805 Result += ",\n";
6806 }
6807 else
6808 Result += "\t0,\n";
6809
6810 if (RefedProtocols.size() > 0) {
6811 Result += "\t(const struct _protocol_list_t *)&";
6812 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6813 Result += ClassName; Result += "_$_"; Result += CatName;
6814 Result += ",\n";
6815 }
6816 else
6817 Result += "\t0,\n";
6818
6819 if (ClassProperties.size() > 0) {
6820 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6821 Result += ClassName; Result += "_$_"; Result += CatName;
6822 Result += ",\n";
6823 }
6824 else
6825 Result += "\t0,\n";
6826
6827 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006828
6829 // Add static function to initialize the class pointer in the category structure.
6830 Result += "static void OBJC_CATEGORY_SETUP_$_";
6831 Result += ClassDecl->getNameAsString();
6832 Result += "_$_";
6833 Result += CatName;
6834 Result += "(void ) {\n";
6835 Result += "\t_OBJC_$_CATEGORY_";
6836 Result += ClassDecl->getNameAsString();
6837 Result += "_$_";
6838 Result += CatName;
6839 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6840 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006841}
6842
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006843static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6844 ASTContext *Context, std::string &Result,
6845 ArrayRef<ObjCMethodDecl *> Methods,
6846 StringRef VarName,
6847 StringRef ProtocolName) {
6848 if (Methods.size() == 0)
6849 return;
6850
6851 Result += "\nstatic const char *";
6852 Result += VarName; Result += ProtocolName;
6853 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6854 Result += "{\n";
6855 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6856 ObjCMethodDecl *MD = Methods[i];
6857 std::string MethodTypeString, QuoteMethodTypeString;
6858 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6859 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6860 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6861 if (i == e-1)
6862 Result += "\n};\n";
6863 else {
6864 Result += ",\n";
6865 }
6866 }
6867}
6868
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006869static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6870 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006871 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006872 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006873 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006874 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6875 // this is what happens:
6876 /**
6877 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6878 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6879 Class->getVisibility() == HiddenVisibility)
6880 Visibility shoud be: HiddenVisibility;
6881 else
6882 Visibility shoud be: DefaultVisibility;
6883 */
6884
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006885 Result += "\n";
6886 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6887 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006888 if (Context->getLangOpts().MicrosoftExt)
6889 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6890
6891 if (!Context->getLangOpts().MicrosoftExt ||
6892 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006893 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006894 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006895 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006896 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006897 if (Ivars[i]->isBitField())
6898 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6899 else
6900 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006901 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6902 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006903 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6904 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006905 if (Ivars[i]->isBitField()) {
6906 // skip over rest of the ivar bitfields.
6907 SKIP_BITFIELDS(i , e, Ivars);
6908 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006909 }
6910}
6911
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006912static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6913 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006914 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006915 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006916 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006917 if (OriginalIvars.size() > 0) {
6918 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6919 SmallVector<ObjCIvarDecl *, 8> Ivars;
6920 // strip off all but the first ivar bitfield from each group of ivars.
6921 // Such ivars in the ivar list table will be replaced by their grouping struct
6922 // 'ivar'.
6923 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6924 if (OriginalIvars[i]->isBitField()) {
6925 Ivars.push_back(OriginalIvars[i]);
6926 // skip over rest of the ivar bitfields.
6927 SKIP_BITFIELDS(i , e, OriginalIvars);
6928 }
6929 else
6930 Ivars.push_back(OriginalIvars[i]);
6931 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006932
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006933 Result += "\nstatic ";
6934 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6935 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006936 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006937 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6938 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6939 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6940 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6941 ObjCIvarDecl *IvarDecl = Ivars[i];
6942 if (i == 0)
6943 Result += "\t{{";
6944 else
6945 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006946 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006947 if (Ivars[i]->isBitField())
6948 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6949 else
6950 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006951 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006952
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006953 Result += "\"";
6954 if (Ivars[i]->isBitField())
6955 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6956 else
6957 Result += IvarDecl->getName();
6958 Result += "\", ";
6959
6960 QualType IVQT = IvarDecl->getType();
6961 if (IvarDecl->isBitField())
6962 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6963
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006964 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006965 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006966 IvarDecl);
6967 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6968 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6969
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006970 // FIXME. this alignment represents the host alignment and need be changed to
6971 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006972 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006973 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006974 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006975 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006976 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006977 if (i == e-1)
6978 Result += "}}\n";
6979 else
6980 Result += "},\n";
6981 }
6982 Result += "};\n";
6983 }
6984}
6985
Fariborz Jahanian11671902012-02-07 17:11:38 +00006986/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006987void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6988 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006989
Fariborz Jahanian11671902012-02-07 17:11:38 +00006990 // Do not synthesize the protocol more than once.
6991 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6992 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006993 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006994
6995 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6996 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006997 // Must write out all protocol definitions in current qualifier list,
6998 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006999 for (auto *I : PDecl->protocols())
7000 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007001
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007002 // Construct method lists.
7003 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7004 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007005 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007006 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7007 OptInstanceMethods.push_back(MD);
7008 } else {
7009 InstanceMethods.push_back(MD);
7010 }
7011 }
7012
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007013 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007014 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7015 OptClassMethods.push_back(MD);
7016 } else {
7017 ClassMethods.push_back(MD);
7018 }
7019 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007020 std::vector<ObjCMethodDecl *> AllMethods;
7021 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7022 AllMethods.push_back(InstanceMethods[i]);
7023 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7024 AllMethods.push_back(ClassMethods[i]);
7025 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7026 AllMethods.push_back(OptInstanceMethods[i]);
7027 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7028 AllMethods.push_back(OptClassMethods[i]);
7029
7030 Write__extendedMethodTypes_initializer(*this, Context, Result,
7031 AllMethods,
7032 "_OBJC_PROTOCOL_METHOD_TYPES_",
7033 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007034 // Protocol's super protocol list
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007035 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007036 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7037 "_OBJC_PROTOCOL_REFS_",
7038 PDecl->getNameAsString());
7039
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007040 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007041 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007042 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007043
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007044 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007045 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007046 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007047
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007048 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007049 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007050 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007051
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007052 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007053 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007054 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007055
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007056 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007057 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007058 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007059 /* Container */0,
7060 "_OBJC_PROTOCOL_PROPERTIES_",
7061 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007062
Fariborz Jahanian48985802012-02-08 00:50:52 +00007063 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007064 Result += "\n";
7065 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007066 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007067 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007068 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007069 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7070 Result += "\t0,\n"; // id is; is null
7071 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007072 if (SuperProtocols.size() > 0) {
7073 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7074 Result += PDecl->getNameAsString(); Result += ",\n";
7075 }
7076 else
7077 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007078 if (InstanceMethods.size() > 0) {
7079 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7080 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007081 }
7082 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007083 Result += "\t0,\n";
7084
7085 if (ClassMethods.size() > 0) {
7086 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7087 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007088 }
7089 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007090 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007091
Fariborz Jahanian48985802012-02-08 00:50:52 +00007092 if (OptInstanceMethods.size() > 0) {
7093 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7094 Result += PDecl->getNameAsString(); Result += ",\n";
7095 }
7096 else
7097 Result += "\t0,\n";
7098
7099 if (OptClassMethods.size() > 0) {
7100 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7101 Result += PDecl->getNameAsString(); Result += ",\n";
7102 }
7103 else
7104 Result += "\t0,\n";
7105
7106 if (ProtocolProperties.size() > 0) {
7107 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7108 Result += PDecl->getNameAsString(); Result += ",\n";
7109 }
7110 else
7111 Result += "\t0,\n";
7112
7113 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7114 Result += "\t0,\n";
7115
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007116 if (AllMethods.size() > 0) {
7117 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7118 Result += PDecl->getNameAsString();
7119 Result += "\n};\n";
7120 }
7121 else
7122 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007123
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007124 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007125 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007126 Result += "struct _protocol_t *";
7127 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7128 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7129 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007130
Fariborz Jahanian11671902012-02-07 17:11:38 +00007131 // Mark this protocol as having been generated.
7132 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7133 llvm_unreachable("protocol already synthesized");
7134
7135}
7136
7137void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7138 const ObjCList<ObjCProtocolDecl> &Protocols,
7139 StringRef prefix, StringRef ClassName,
7140 std::string &Result) {
7141 if (Protocols.empty()) return;
7142
7143 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007144 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007145
7146 // Output the top lovel protocol meta-data for the class.
7147 /* struct _objc_protocol_list {
7148 struct _objc_protocol_list *next;
7149 int protocol_count;
7150 struct _objc_protocol *class_protocols[];
7151 }
7152 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007153 Result += "\n";
7154 if (LangOpts.MicrosoftExt)
7155 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7156 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007157 Result += "\tstruct _objc_protocol_list *next;\n";
7158 Result += "\tint protocol_count;\n";
7159 Result += "\tstruct _objc_protocol *class_protocols[";
7160 Result += utostr(Protocols.size());
7161 Result += "];\n} _OBJC_";
7162 Result += prefix;
7163 Result += "_PROTOCOLS_";
7164 Result += ClassName;
7165 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7166 "{\n\t0, ";
7167 Result += utostr(Protocols.size());
7168 Result += "\n";
7169
7170 Result += "\t,{&_OBJC_PROTOCOL_";
7171 Result += Protocols[0]->getNameAsString();
7172 Result += " \n";
7173
7174 for (unsigned i = 1; i != Protocols.size(); i++) {
7175 Result += "\t ,&_OBJC_PROTOCOL_";
7176 Result += Protocols[i]->getNameAsString();
7177 Result += "\n";
7178 }
7179 Result += "\t }\n};\n";
7180}
7181
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007182/// hasObjCExceptionAttribute - Return true if this class or any super
7183/// class has the __objc_exception__ attribute.
7184/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7185static bool hasObjCExceptionAttribute(ASTContext &Context,
7186 const ObjCInterfaceDecl *OID) {
7187 if (OID->hasAttr<ObjCExceptionAttr>())
7188 return true;
7189 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7190 return hasObjCExceptionAttribute(Context, Super);
7191 return false;
7192}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007193
Fariborz Jahanian11671902012-02-07 17:11:38 +00007194void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7195 std::string &Result) {
7196 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7197
7198 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007199 if (CDecl->isImplicitInterfaceDecl())
7200 assert(false &&
7201 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007202
Fariborz Jahanian45489622012-03-14 18:09:23 +00007203 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007204 SmallVector<ObjCIvarDecl *, 8> IVars;
7205
7206 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7207 IVD; IVD = IVD->getNextIvar()) {
7208 // Ignore unnamed bit-fields.
7209 if (!IVD->getDeclName())
7210 continue;
7211 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007212 }
7213
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007214 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007215 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007216 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007217
7218 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007219 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007220
7221 // If any of our property implementations have associated getters or
7222 // setters, produce metadata for them as well.
7223 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7224 PropEnd = IDecl->propimpl_end();
7225 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007226 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007227 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007228 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007229 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007230 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007231 if (!PD)
7232 continue;
7233 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007234 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007235 InstanceMethods.push_back(Getter);
7236 if (PD->isReadOnly())
7237 continue;
7238 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007239 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007240 InstanceMethods.push_back(Setter);
7241 }
7242
7243 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7244 "_OBJC_$_INSTANCE_METHODS_",
7245 IDecl->getNameAsString(), true);
7246
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007247 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007248
7249 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7250 "_OBJC_$_CLASS_METHODS_",
7251 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007252
7253 // Protocols referenced in class declaration?
7254 // Protocol's super protocol list
7255 std::vector<ObjCProtocolDecl *> RefedProtocols;
7256 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7257 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7258 E = Protocols.end();
7259 I != E; ++I) {
7260 RefedProtocols.push_back(*I);
7261 // Must write out all protocol definitions in current qualifier list,
7262 // and in their nested qualifiers before writing out current definition.
7263 RewriteObjCProtocolMetaData(*I, Result);
7264 }
7265
7266 Write_protocol_list_initializer(Context, Result,
7267 RefedProtocols,
7268 "_OBJC_CLASS_PROTOCOLS_$_",
7269 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007270
7271 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007272 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007273 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007274 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007275 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007276 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007277
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007278
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007279 // Data for initializing _class_ro_t metaclass meta-data
7280 uint32_t flags = CLS_META;
7281 std::string InstanceSize;
7282 std::string InstanceStart;
7283
7284
7285 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7286 if (classIsHidden)
7287 flags |= OBJC2_CLS_HIDDEN;
7288
7289 if (!CDecl->getSuperClass())
7290 // class is root
7291 flags |= CLS_ROOT;
7292 InstanceSize = "sizeof(struct _class_t)";
7293 InstanceStart = InstanceSize;
7294 Write__class_ro_t_initializer(Context, Result, flags,
7295 InstanceStart, InstanceSize,
7296 ClassMethods,
7297 0,
7298 0,
7299 0,
7300 "_OBJC_METACLASS_RO_$_",
7301 CDecl->getNameAsString());
7302
7303
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007304 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007305 flags = CLS;
7306 if (classIsHidden)
7307 flags |= OBJC2_CLS_HIDDEN;
7308
7309 if (hasObjCExceptionAttribute(*Context, CDecl))
7310 flags |= CLS_EXCEPTION;
7311
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007312 if (!CDecl->getSuperClass())
7313 // class is root
7314 flags |= CLS_ROOT;
7315
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007316 InstanceSize.clear();
7317 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007318 if (!ObjCSynthesizedStructs.count(CDecl)) {
7319 InstanceSize = "0";
7320 InstanceStart = "0";
7321 }
7322 else {
7323 InstanceSize = "sizeof(struct ";
7324 InstanceSize += CDecl->getNameAsString();
7325 InstanceSize += "_IMPL)";
7326
7327 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7328 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007329 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007330 }
7331 else
7332 InstanceStart = InstanceSize;
7333 }
7334 Write__class_ro_t_initializer(Context, Result, flags,
7335 InstanceStart, InstanceSize,
7336 InstanceMethods,
7337 RefedProtocols,
7338 IVars,
7339 ClassProperties,
7340 "_OBJC_CLASS_RO_$_",
7341 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007342
7343 Write_class_t(Context, Result,
7344 "OBJC_METACLASS_$_",
7345 CDecl, /*metaclass*/true);
7346
7347 Write_class_t(Context, Result,
7348 "OBJC_CLASS_$_",
7349 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007350
7351 if (ImplementationIsNonLazy(IDecl))
7352 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007353
Fariborz Jahanian11671902012-02-07 17:11:38 +00007354}
7355
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007356void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7357 int ClsDefCount = ClassImplementation.size();
7358 if (!ClsDefCount)
7359 return;
7360 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7361 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7362 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7363 for (int i = 0; i < ClsDefCount; i++) {
7364 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7365 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7366 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7367 Result += CDecl->getName(); Result += ",\n";
7368 }
7369 Result += "};\n";
7370}
7371
Fariborz Jahanian11671902012-02-07 17:11:38 +00007372void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7373 int ClsDefCount = ClassImplementation.size();
7374 int CatDefCount = CategoryImplementation.size();
7375
7376 // For each implemented class, write out all its meta data.
7377 for (int i = 0; i < ClsDefCount; i++)
7378 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7379
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007380 RewriteClassSetupInitHook(Result);
7381
Fariborz Jahanian11671902012-02-07 17:11:38 +00007382 // For each implemented category, write out all its meta data.
7383 for (int i = 0; i < CatDefCount; i++)
7384 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7385
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007386 RewriteCategorySetupInitHook(Result);
7387
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007388 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007389 if (LangOpts.MicrosoftExt)
7390 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007391 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7392 Result += llvm::utostr(ClsDefCount); Result += "]";
7393 Result +=
7394 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7395 "regular,no_dead_strip\")))= {\n";
7396 for (int i = 0; i < ClsDefCount; i++) {
7397 Result += "\t&OBJC_CLASS_$_";
7398 Result += ClassImplementation[i]->getNameAsString();
7399 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007400 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007401 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007402
7403 if (!DefinedNonLazyClasses.empty()) {
7404 if (LangOpts.MicrosoftExt)
7405 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7406 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7407 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7408 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7409 Result += ",\n";
7410 }
7411 Result += "};\n";
7412 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007413 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007414
7415 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007416 if (LangOpts.MicrosoftExt)
7417 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007418 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7419 Result += llvm::utostr(CatDefCount); Result += "]";
7420 Result +=
7421 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7422 "regular,no_dead_strip\")))= {\n";
7423 for (int i = 0; i < CatDefCount; i++) {
7424 Result += "\t&_OBJC_$_CATEGORY_";
7425 Result +=
7426 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7427 Result += "_$_";
7428 Result += CategoryImplementation[i]->getNameAsString();
7429 Result += ",\n";
7430 }
7431 Result += "};\n";
7432 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007433
7434 if (!DefinedNonLazyCategories.empty()) {
7435 if (LangOpts.MicrosoftExt)
7436 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7437 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7438 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7439 Result += "\t&_OBJC_$_CATEGORY_";
7440 Result +=
7441 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7442 Result += "_$_";
7443 Result += DefinedNonLazyCategories[i]->getNameAsString();
7444 Result += ",\n";
7445 }
7446 Result += "};\n";
7447 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007448}
7449
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007450void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7451 if (LangOpts.MicrosoftExt)
7452 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7453
7454 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7455 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007456 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007457}
7458
Fariborz Jahanian11671902012-02-07 17:11:38 +00007459/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7460/// implementation.
7461void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7462 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007463 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007464 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7465 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007466 ObjCCategoryDecl *CDecl
7467 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007468
7469 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007470 FullCategoryName += "_$_";
7471 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007472
7473 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007474 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007475
7476 // If any of our property implementations have associated getters or
7477 // setters, produce metadata for them as well.
7478 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7479 PropEnd = IDecl->propimpl_end();
7480 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007481 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007482 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007483 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007484 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007485 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007486 if (!PD)
7487 continue;
7488 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7489 InstanceMethods.push_back(Getter);
7490 if (PD->isReadOnly())
7491 continue;
7492 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7493 InstanceMethods.push_back(Setter);
7494 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007495
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007496 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7497 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7498 FullCategoryName, true);
7499
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007500 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007501
7502 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7503 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7504 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007505
7506 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007507 // Protocol's super protocol list
7508 std::vector<ObjCProtocolDecl *> RefedProtocols;
Aaron Ballmana49c5062014-03-13 20:29:09 +00007509 for (ObjCCategoryDecl::protocol_iterator I = CDecl->protocol_begin(),
7510 E = CDecl->protocol_end();
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00007511
7512 I != E; ++I) {
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007513 RefedProtocols.push_back(*I);
7514 // Must write out all protocol definitions in current qualifier list,
7515 // and in their nested qualifiers before writing out current definition.
7516 RewriteObjCProtocolMetaData(*I, Result);
7517 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007518
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007519 Write_protocol_list_initializer(Context, Result,
7520 RefedProtocols,
7521 "_OBJC_CATEGORY_PROTOCOLS_$_",
7522 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007523
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007524 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007525 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007526 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007527 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007528 "_OBJC_$_PROP_LIST_",
7529 FullCategoryName);
7530
7531 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007532 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007533 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007534 InstanceMethods,
7535 ClassMethods,
7536 RefedProtocols,
7537 ClassProperties);
7538
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007539 // Determine if this category is also "non-lazy".
7540 if (ImplementationIsNonLazy(IDecl))
7541 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007542
7543}
7544
7545void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7546 int CatDefCount = CategoryImplementation.size();
7547 if (!CatDefCount)
7548 return;
7549 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7550 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7551 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7552 for (int i = 0; i < CatDefCount; i++) {
7553 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7554 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7555 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7556 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7557 Result += ClassDecl->getName();
7558 Result += "_$_";
7559 Result += CatDecl->getName();
7560 Result += ",\n";
7561 }
7562 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007563}
7564
7565// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7566/// class methods.
7567template<typename MethodIterator>
7568void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7569 MethodIterator MethodEnd,
7570 bool IsInstanceMethod,
7571 StringRef prefix,
7572 StringRef ClassName,
7573 std::string &Result) {
7574 if (MethodBegin == MethodEnd) return;
7575
7576 if (!objc_impl_method) {
7577 /* struct _objc_method {
7578 SEL _cmd;
7579 char *method_types;
7580 void *_imp;
7581 }
7582 */
7583 Result += "\nstruct _objc_method {\n";
7584 Result += "\tSEL _cmd;\n";
7585 Result += "\tchar *method_types;\n";
7586 Result += "\tvoid *_imp;\n";
7587 Result += "};\n";
7588
7589 objc_impl_method = true;
7590 }
7591
7592 // Build _objc_method_list for class's methods if needed
7593
7594 /* struct {
7595 struct _objc_method_list *next_method;
7596 int method_count;
7597 struct _objc_method method_list[];
7598 }
7599 */
7600 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007601 Result += "\n";
7602 if (LangOpts.MicrosoftExt) {
7603 if (IsInstanceMethod)
7604 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7605 else
7606 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7607 }
7608 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007609 Result += "\tstruct _objc_method_list *next_method;\n";
7610 Result += "\tint method_count;\n";
7611 Result += "\tstruct _objc_method method_list[";
7612 Result += utostr(NumMethods);
7613 Result += "];\n} _OBJC_";
7614 Result += prefix;
7615 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7616 Result += "_METHODS_";
7617 Result += ClassName;
7618 Result += " __attribute__ ((used, section (\"__OBJC, __";
7619 Result += IsInstanceMethod ? "inst" : "cls";
7620 Result += "_meth\")))= ";
7621 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7622
7623 Result += "\t,{{(SEL)\"";
7624 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7625 std::string MethodTypeString;
7626 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7627 Result += "\", \"";
7628 Result += MethodTypeString;
7629 Result += "\", (void *)";
7630 Result += MethodInternalNames[*MethodBegin];
7631 Result += "}\n";
7632 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7633 Result += "\t ,{(SEL)\"";
7634 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7635 std::string MethodTypeString;
7636 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7637 Result += "\", \"";
7638 Result += MethodTypeString;
7639 Result += "\", (void *)";
7640 Result += MethodInternalNames[*MethodBegin];
7641 Result += "}\n";
7642 }
7643 Result += "\t }\n};\n";
7644}
7645
7646Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7647 SourceRange OldRange = IV->getSourceRange();
7648 Expr *BaseExpr = IV->getBase();
7649
7650 // Rewrite the base, but without actually doing replaces.
7651 {
7652 DisableReplaceStmtScope S(*this);
7653 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7654 IV->setBase(BaseExpr);
7655 }
7656
7657 ObjCIvarDecl *D = IV->getDecl();
7658
7659 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007660
Fariborz Jahanian11671902012-02-07 17:11:38 +00007661 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7662 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007663 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007664 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7665 // lookup which class implements the instance variable.
7666 ObjCInterfaceDecl *clsDeclared = 0;
7667 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7668 clsDeclared);
7669 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7670
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007671 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007672 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007673 if (D->isBitField())
7674 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7675 else
7676 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007677
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007678 ReferencedIvars[clsDeclared].insert(D);
7679
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007680 // cast offset to "char *".
7681 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7682 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007683 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007684 BaseExpr);
7685 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7686 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007687 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007688 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7689 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007690 SourceLocation());
7691 BinaryOperator *addExpr =
7692 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7693 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007694 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007695 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007696 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7697 SourceLocation(),
7698 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007699 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007700 if (D->isBitField())
7701 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007702
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007703 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007704 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007705 RD = RD->getDefinition();
7706 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007707 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007708 ObjCContainerDecl *CDecl =
7709 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7710 // ivar in class extensions requires special treatment.
7711 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7712 CDecl = CatDecl->getClassInterface();
7713 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007714 RecName += "_IMPL";
7715 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7716 SourceLocation(), SourceLocation(),
7717 &Context->Idents.get(RecName.c_str()));
7718 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7719 unsigned UnsignedIntSize =
7720 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7721 Expr *Zero = IntegerLiteral::Create(*Context,
7722 llvm::APInt(UnsignedIntSize, 0),
7723 Context->UnsignedIntTy, SourceLocation());
7724 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7725 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7726 Zero);
7727 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7728 SourceLocation(),
7729 &Context->Idents.get(D->getNameAsString()),
7730 IvarT, 0,
7731 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007732 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007733 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7734 FD->getType(), VK_LValue,
7735 OK_Ordinary);
7736 IvarT = Context->getDecltypeType(ME, ME->getType());
7737 }
7738 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007739 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007740 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007741
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007742 castExpr = NoTypeInfoCStyleCastExpr(Context,
7743 castT,
7744 CK_BitCast,
7745 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007746
7747
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007748 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007749 VK_LValue, OK_Ordinary,
7750 SourceLocation());
7751 PE = new (Context) ParenExpr(OldRange.getBegin(),
7752 OldRange.getEnd(),
7753 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007754
7755 if (D->isBitField()) {
7756 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7757 SourceLocation(),
7758 &Context->Idents.get(D->getNameAsString()),
7759 D->getType(), 0,
7760 /*BitWidth=*/D->getBitWidth(),
7761 /*Mutable=*/true,
7762 ICIS_NoInit);
7763 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7764 FD->getType(), VK_LValue,
7765 OK_Ordinary);
7766 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007767
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007768 }
7769 else
7770 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007771 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007772
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007773 ReplaceStmtWithRange(IV, Replacement, OldRange);
7774 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007775}