blob: 9b86492051a727bd430a5af00e1feb5afa581e6e [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"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
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 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000610 };
611
612}
613
614void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
615 NamedDecl *D) {
616 if (const FunctionProtoType *fproto
617 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000618 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
619 E = fproto->param_type_end();
620 I && (I != E); ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000621 if (isTopLevelBlockPointerType(*I)) {
622 // All the args are checked/rewritten. Don't call twice!
623 RewriteBlockPointerDecl(D);
624 break;
625 }
626 }
627}
628
629void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
630 const PointerType *PT = funcType->getAs<PointerType>();
631 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
632 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
633}
634
635static bool IsHeaderFile(const std::string &Filename) {
636 std::string::size_type DotPos = Filename.rfind('.');
637
638 if (DotPos == std::string::npos) {
639 // no file extension
640 return false;
641 }
642
643 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
644 // C header: .h
645 // C++ header: .hh or .H;
646 return Ext == "h" || Ext == "hh" || Ext == "H";
647}
648
649RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
650 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000651 bool silenceMacroWarn,
652 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000653 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000654 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000655 IsHeader = IsHeaderFile(inFile);
656 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
657 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000658 // FIXME. This should be an error. But if block is not called, it is OK. And it
659 // may break including some headers.
660 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
661 "rewriting block literal declared in global scope is not implemented");
662
Fariborz Jahanian11671902012-02-07 17:11:38 +0000663 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
664 DiagnosticsEngine::Warning,
665 "rewriter doesn't support user-specified control flow semantics "
666 "for @try/@finally (code may not execute properly)");
667}
668
669ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
670 raw_ostream* OS,
671 DiagnosticsEngine &Diags,
672 const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000673 bool SilenceRewriteMacroWarning,
674 bool LineInfo) {
675 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
676 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000677}
678
679void RewriteModernObjC::InitializeCommon(ASTContext &context) {
680 Context = &context;
681 SM = &Context->getSourceManager();
682 TUDecl = Context->getTranslationUnitDecl();
683 MsgSendFunctionDecl = 0;
684 MsgSendSuperFunctionDecl = 0;
685 MsgSendStretFunctionDecl = 0;
686 MsgSendSuperStretFunctionDecl = 0;
687 MsgSendFpretFunctionDecl = 0;
688 GetClassFunctionDecl = 0;
689 GetMetaClassFunctionDecl = 0;
690 GetSuperClassFunctionDecl = 0;
691 SelGetUidFunctionDecl = 0;
692 CFStringFunctionDecl = 0;
693 ConstantStringClassReference = 0;
694 NSStringRecord = 0;
695 CurMethodDef = 0;
696 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000697 GlobalVarDecl = 0;
Fariborz Jahaniane0050702012-03-23 00:00:49 +0000698 GlobalConstructionExp = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000699 SuperStructDecl = 0;
700 ProtocolTypeDecl = 0;
701 ConstantStringDecl = 0;
702 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000703 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000704 NumObjCStringLiterals = 0;
705 PropParentMap = 0;
706 CurrentBody = 0;
707 DisableReplaceStmt = false;
708 objc_impl_method = false;
709
710 // Get the ID and start/end of the main file.
711 MainFileID = SM->getMainFileID();
712 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
713 MainFileStart = MainBuf->getBufferStart();
714 MainFileEnd = MainBuf->getBufferEnd();
715
David Blaikiebbafb8a2012-03-11 07:00:24 +0000716 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000717}
718
719//===----------------------------------------------------------------------===//
720// Top Level Driver Code
721//===----------------------------------------------------------------------===//
722
723void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
724 if (Diags.hasErrorOccurred())
725 return;
726
727 // Two cases: either the decl could be in the main file, or it could be in a
728 // #included file. If the former, rewrite it now. If the later, check to see
729 // if we rewrote the #include/#import.
730 SourceLocation Loc = D->getLocation();
731 Loc = SM->getExpansionLoc(Loc);
732
733 // If this is for a builtin, ignore it.
734 if (Loc.isInvalid()) return;
735
736 // Look for built-in declarations that we need to refer during the rewrite.
737 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
738 RewriteFunctionDecl(FD);
739 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
740 // declared in <Foundation/NSString.h>
741 if (FVD->getName() == "_NSConstantStringClassReference") {
742 ConstantStringClassReference = FVD;
743 return;
744 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000745 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
746 RewriteCategoryDecl(CD);
747 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
748 if (PD->isThisDeclarationADefinition())
749 RewriteProtocolDecl(PD);
750 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000751 // FIXME. This will not work in all situations and leaving it out
752 // is harmless.
753 // RewriteLinkageSpec(LSD);
754
Fariborz Jahanian11671902012-02-07 17:11:38 +0000755 // Recurse into linkage specifications
756 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
757 DIEnd = LSD->decls_end();
758 DI != DIEnd; ) {
759 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
760 if (!IFace->isThisDeclarationADefinition()) {
761 SmallVector<Decl *, 8> DG;
762 SourceLocation StartLoc = IFace->getLocStart();
763 do {
764 if (isa<ObjCInterfaceDecl>(*DI) &&
765 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
766 StartLoc == (*DI)->getLocStart())
767 DG.push_back(*DI);
768 else
769 break;
770
771 ++DI;
772 } while (DI != DIEnd);
773 RewriteForwardClassDecl(DG);
774 continue;
775 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000776 else {
777 // Keep track of all interface declarations seen.
778 ObjCInterfacesSeen.push_back(IFace);
779 ++DI;
780 continue;
781 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000782 }
783
784 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
785 if (!Proto->isThisDeclarationADefinition()) {
786 SmallVector<Decl *, 8> DG;
787 SourceLocation StartLoc = Proto->getLocStart();
788 do {
789 if (isa<ObjCProtocolDecl>(*DI) &&
790 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
791 StartLoc == (*DI)->getLocStart())
792 DG.push_back(*DI);
793 else
794 break;
795
796 ++DI;
797 } while (DI != DIEnd);
798 RewriteForwardProtocolDecl(DG);
799 continue;
800 }
801 }
802
803 HandleTopLevelSingleDecl(*DI);
804 ++DI;
805 }
806 }
807 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000808 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000809 return HandleDeclInMainFile(D);
810}
811
812//===----------------------------------------------------------------------===//
813// Syntactic (non-AST) Rewriting Code
814//===----------------------------------------------------------------------===//
815
816void RewriteModernObjC::RewriteInclude() {
817 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
818 StringRef MainBuf = SM->getBufferData(MainFileID);
819 const char *MainBufStart = MainBuf.begin();
820 const char *MainBufEnd = MainBuf.end();
821 size_t ImportLen = strlen("import");
822
823 // Loop over the whole file, looking for includes.
824 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
825 if (*BufPtr == '#') {
826 if (++BufPtr == MainBufEnd)
827 return;
828 while (*BufPtr == ' ' || *BufPtr == '\t')
829 if (++BufPtr == MainBufEnd)
830 return;
831 if (!strncmp(BufPtr, "import", ImportLen)) {
832 // replace import with include
833 SourceLocation ImportLoc =
834 LocStart.getLocWithOffset(BufPtr-MainBufStart);
835 ReplaceText(ImportLoc, ImportLen, "include");
836 BufPtr += ImportLen;
837 }
838 }
839 }
840}
841
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000842static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
843 ObjCIvarDecl *IvarDecl, std::string &Result) {
844 Result += "OBJC_IVAR_$_";
845 Result += IDecl->getName();
846 Result += "$";
847 Result += IvarDecl->getName();
848}
849
850std::string
851RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
852 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
853
854 // Build name of symbol holding ivar offset.
855 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000856 if (D->isBitField())
857 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
858 else
859 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000860
861
862 std::string S = "(*(";
863 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000864 if (D->isBitField())
865 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000866
867 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
868 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
869 RD = RD->getDefinition();
870 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
871 // decltype(((Foo_IMPL*)0)->bar) *
872 ObjCContainerDecl *CDecl =
873 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
874 // ivar in class extensions requires special treatment.
875 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
876 CDecl = CatDecl->getClassInterface();
877 std::string RecName = CDecl->getName();
878 RecName += "_IMPL";
879 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
880 SourceLocation(), SourceLocation(),
881 &Context->Idents.get(RecName.c_str()));
882 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
883 unsigned UnsignedIntSize =
884 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
885 Expr *Zero = IntegerLiteral::Create(*Context,
886 llvm::APInt(UnsignedIntSize, 0),
887 Context->UnsignedIntTy, SourceLocation());
888 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
889 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
890 Zero);
891 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
892 SourceLocation(),
893 &Context->Idents.get(D->getNameAsString()),
894 IvarT, 0,
895 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +0000896 ICIS_NoInit);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000897 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
898 FD->getType(), VK_LValue,
899 OK_Ordinary);
900 IvarT = Context->getDecltypeType(ME, ME->getType());
901 }
902 }
903 convertObjCTypeToCStyleType(IvarT);
904 QualType castT = Context->getPointerType(IvarT);
905 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
906 S += TypeString;
907 S += ")";
908
909 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
910 S += "((char *)self + ";
911 S += IvarOffsetName;
912 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000913 if (D->isBitField()) {
914 S += ".";
915 S += D->getNameAsString();
916 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000917 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000918 return S;
919}
920
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000921/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
922/// been found in the class implementation. In this case, it must be synthesized.
923static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
924 ObjCPropertyDecl *PD,
925 bool getter) {
926 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
927 : !IMP->getInstanceMethod(PD->getSetterName());
928
929}
930
Fariborz Jahanian11671902012-02-07 17:11:38 +0000931void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
932 ObjCImplementationDecl *IMD,
933 ObjCCategoryImplDecl *CID) {
934 static bool objcGetPropertyDefined = false;
935 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000936 SourceLocation startGetterSetterLoc;
937
938 if (PID->getLocStart().isValid()) {
939 SourceLocation startLoc = PID->getLocStart();
940 InsertText(startLoc, "// ");
941 const char *startBuf = SM->getCharacterData(startLoc);
942 assert((*startBuf == '@') && "bogus @synthesize location");
943 const char *semiBuf = strchr(startBuf, ';');
944 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
945 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
946 }
947 else
948 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000949
950 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
951 return; // FIXME: is this correct?
952
953 // Generate the 'getter' function.
954 ObjCPropertyDecl *PD = PID->getPropertyDecl();
955 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000956 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957
Bill Wendling44426052012-12-20 19:22:21 +0000958 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000959 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000960 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
961 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000962 ObjCPropertyDecl::OBJC_PR_copy));
963 std::string Getr;
964 if (GenGetProperty && !objcGetPropertyDefined) {
965 objcGetPropertyDefined = true;
966 // FIXME. Is this attribute correct in all cases?
967 Getr = "\nextern \"C\" __declspec(dllimport) "
968 "id objc_getProperty(id, SEL, long, bool);\n";
969 }
970 RewriteObjCMethodDecl(OID->getContainingInterface(),
971 PD->getGetterMethodDecl(), Getr);
972 Getr += "{ ";
973 // Synthesize an explicit cast to gain access to the ivar.
974 // See objc-act.c:objc_synthesize_new_getter() for details.
975 if (GenGetProperty) {
976 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
977 Getr += "typedef ";
978 const FunctionType *FPRetType = 0;
Alp Toker314cc812014-01-25 16:55:45 +0000979 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000980 FPRetType);
981 Getr += " _TYPE";
982 if (FPRetType) {
983 Getr += ")"; // close the precedence "scope" for "*".
984
985 // Now, emit the argument types (if any).
986 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
987 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000988 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000989 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000990 std::string ParamStr =
991 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000992 Getr += ParamStr;
993 }
994 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000995 if (FT->getNumParams())
996 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +0000997 Getr += "...";
998 }
999 Getr += ")";
1000 } else
1001 Getr += "()";
1002 }
1003 Getr += ";\n";
1004 Getr += "return (_TYPE)";
1005 Getr += "objc_getProperty(self, _cmd, ";
1006 RewriteIvarOffsetComputation(OID, Getr);
1007 Getr += ", 1)";
1008 }
1009 else
1010 Getr += "return " + getIvarAccessString(OID);
1011 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001012 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001013 }
1014
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001015 if (PD->isReadOnly() ||
1016 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001017 return;
1018
1019 // Generate the 'setter' function.
1020 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001021 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001022 ObjCPropertyDecl::OBJC_PR_copy);
1023 if (GenSetProperty && !objcSetPropertyDefined) {
1024 objcSetPropertyDefined = true;
1025 // FIXME. Is this attribute correct in all cases?
1026 Setr = "\nextern \"C\" __declspec(dllimport) "
1027 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1028 }
1029
1030 RewriteObjCMethodDecl(OID->getContainingInterface(),
1031 PD->getSetterMethodDecl(), Setr);
1032 Setr += "{ ";
1033 // Synthesize an explicit cast to initialize the ivar.
1034 // See objc-act.c:objc_synthesize_new_setter() for details.
1035 if (GenSetProperty) {
1036 Setr += "objc_setProperty (self, _cmd, ";
1037 RewriteIvarOffsetComputation(OID, Setr);
1038 Setr += ", (id)";
1039 Setr += PD->getName();
1040 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001041 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001042 Setr += "0, ";
1043 else
1044 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001045 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001046 Setr += "1)";
1047 else
1048 Setr += "0)";
1049 }
1050 else {
1051 Setr += getIvarAccessString(OID) + " = ";
1052 Setr += PD->getName();
1053 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001054 Setr += "; }\n";
1055 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001056}
1057
1058static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1059 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001060 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001061 typedefString += ForwardDecl->getNameAsString();
1062 typedefString += "\n";
1063 typedefString += "#define _REWRITER_typedef_";
1064 typedefString += ForwardDecl->getNameAsString();
1065 typedefString += "\n";
1066 typedefString += "typedef struct objc_object ";
1067 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001068 // typedef struct { } _objc_exc_Classname;
1069 typedefString += ";\ntypedef struct {} _objc_exc_";
1070 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001071 typedefString += ";\n#endif\n";
1072}
1073
1074void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1075 const std::string &typedefString) {
1076 SourceLocation startLoc = ClassDecl->getLocStart();
1077 const char *startBuf = SM->getCharacterData(startLoc);
1078 const char *semiPtr = strchr(startBuf, ';');
1079 // Replace the @class with typedefs corresponding to the classes.
1080 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1081}
1082
1083void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1084 std::string typedefString;
1085 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001086 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1087 if (I == D.begin()) {
1088 // Translate to typedef's that forward reference structs with the same name
1089 // as the class. As a convenience, we include the original declaration
1090 // as a comment.
1091 typedefString += "// @class ";
1092 typedefString += ForwardDecl->getNameAsString();
1093 typedefString += ";";
1094 }
1095 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001096 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001097 else
1098 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001099 }
1100 DeclGroupRef::iterator I = D.begin();
1101 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1102}
1103
1104void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001105 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001106 std::string typedefString;
1107 for (unsigned i = 0; i < D.size(); i++) {
1108 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1109 if (i == 0) {
1110 typedefString += "// @class ";
1111 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001112 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001113 }
1114 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1115 }
1116 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1117}
1118
1119void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1120 // When method is a synthesized one, such as a getter/setter there is
1121 // nothing to rewrite.
1122 if (Method->isImplicit())
1123 return;
1124 SourceLocation LocStart = Method->getLocStart();
1125 SourceLocation LocEnd = Method->getLocEnd();
1126
1127 if (SM->getExpansionLineNumber(LocEnd) >
1128 SM->getExpansionLineNumber(LocStart)) {
1129 InsertText(LocStart, "#if 0\n");
1130 ReplaceText(LocEnd, 1, ";\n#endif\n");
1131 } else {
1132 InsertText(LocStart, "// ");
1133 }
1134}
1135
1136void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1137 SourceLocation Loc = prop->getAtLoc();
1138
1139 ReplaceText(Loc, 0, "// ");
1140 // FIXME: handle properties that are declared across multiple lines.
1141}
1142
1143void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1144 SourceLocation LocStart = CatDecl->getLocStart();
1145
1146 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001147 if (CatDecl->getIvarRBraceLoc().isValid()) {
1148 ReplaceText(LocStart, 1, "/** ");
1149 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1150 }
1151 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001152 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001153 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001154
Fariborz Jahanian11671902012-02-07 17:11:38 +00001155 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1156 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001157 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001158
1159 for (ObjCCategoryDecl::instmeth_iterator
1160 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1161 I != E; ++I)
1162 RewriteMethodDeclaration(*I);
1163 for (ObjCCategoryDecl::classmeth_iterator
1164 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1165 I != E; ++I)
1166 RewriteMethodDeclaration(*I);
1167
1168 // Lastly, comment out the @end.
1169 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001170 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001171}
1172
1173void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1174 SourceLocation LocStart = PDecl->getLocStart();
1175 assert(PDecl->isThisDeclarationADefinition());
1176
1177 // FIXME: handle protocol headers that are declared across multiple lines.
1178 ReplaceText(LocStart, 0, "// ");
1179
1180 for (ObjCProtocolDecl::instmeth_iterator
1181 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1182 I != E; ++I)
1183 RewriteMethodDeclaration(*I);
1184 for (ObjCProtocolDecl::classmeth_iterator
1185 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1186 I != E; ++I)
1187 RewriteMethodDeclaration(*I);
1188
1189 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1190 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001191 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001192
1193 // Lastly, comment out the @end.
1194 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001195 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001196
1197 // Must comment out @optional/@required
1198 const char *startBuf = SM->getCharacterData(LocStart);
1199 const char *endBuf = SM->getCharacterData(LocEnd);
1200 for (const char *p = startBuf; p < endBuf; p++) {
1201 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1202 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1203 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1204
1205 }
1206 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1207 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1208 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1209
1210 }
1211 }
1212}
1213
1214void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1215 SourceLocation LocStart = (*D.begin())->getLocStart();
1216 if (LocStart.isInvalid())
1217 llvm_unreachable("Invalid SourceLocation");
1218 // FIXME: handle forward protocol that are declared across multiple lines.
1219 ReplaceText(LocStart, 0, "// ");
1220}
1221
1222void
Craig Topper5603df42013-07-05 19:34:19 +00001223RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001224 SourceLocation LocStart = DG[0]->getLocStart();
1225 if (LocStart.isInvalid())
1226 llvm_unreachable("Invalid SourceLocation");
1227 // FIXME: handle forward protocol that are declared across multiple lines.
1228 ReplaceText(LocStart, 0, "// ");
1229}
1230
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001231void
1232RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1233 SourceLocation LocStart = LSD->getExternLoc();
1234 if (LocStart.isInvalid())
1235 llvm_unreachable("Invalid extern SourceLocation");
1236
1237 ReplaceText(LocStart, 0, "// ");
1238 if (!LSD->hasBraces())
1239 return;
1240 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1241 SourceLocation LocRBrace = LSD->getRBraceLoc();
1242 if (LocRBrace.isInvalid())
1243 llvm_unreachable("Invalid rbrace SourceLocation");
1244 ReplaceText(LocRBrace, 0, "// ");
1245}
1246
Fariborz Jahanian11671902012-02-07 17:11:38 +00001247void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1248 const FunctionType *&FPRetType) {
1249 if (T->isObjCQualifiedIdType())
1250 ResultStr += "id";
1251 else if (T->isFunctionPointerType() ||
1252 T->isBlockPointerType()) {
1253 // needs special handling, since pointer-to-functions have special
1254 // syntax (where a decaration models use).
1255 QualType retType = T;
1256 QualType PointeeTy;
1257 if (const PointerType* PT = retType->getAs<PointerType>())
1258 PointeeTy = PT->getPointeeType();
1259 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1260 PointeeTy = BPT->getPointeeType();
1261 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001262 ResultStr +=
1263 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001264 ResultStr += "(*";
1265 }
1266 } else
1267 ResultStr += T.getAsString(Context->getPrintingPolicy());
1268}
1269
1270void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1271 ObjCMethodDecl *OMD,
1272 std::string &ResultStr) {
1273 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1274 const FunctionType *FPRetType = 0;
1275 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001276 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001277 ResultStr += " ";
1278
1279 // Unique method name
1280 std::string NameStr;
1281
1282 if (OMD->isInstanceMethod())
1283 NameStr += "_I_";
1284 else
1285 NameStr += "_C_";
1286
1287 NameStr += IDecl->getNameAsString();
1288 NameStr += "_";
1289
1290 if (ObjCCategoryImplDecl *CID =
1291 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1292 NameStr += CID->getNameAsString();
1293 NameStr += "_";
1294 }
1295 // Append selector names, replacing ':' with '_'
1296 {
1297 std::string selString = OMD->getSelector().getAsString();
1298 int len = selString.size();
1299 for (int i = 0; i < len; i++)
1300 if (selString[i] == ':')
1301 selString[i] = '_';
1302 NameStr += selString;
1303 }
1304 // Remember this name for metadata emission
1305 MethodInternalNames[OMD] = NameStr;
1306 ResultStr += NameStr;
1307
1308 // Rewrite arguments
1309 ResultStr += "(";
1310
1311 // invisible arguments
1312 if (OMD->isInstanceMethod()) {
1313 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1314 selfTy = Context->getPointerType(selfTy);
1315 if (!LangOpts.MicrosoftExt) {
1316 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1317 ResultStr += "struct ";
1318 }
1319 // When rewriting for Microsoft, explicitly omit the structure name.
1320 ResultStr += IDecl->getNameAsString();
1321 ResultStr += " *";
1322 }
1323 else
1324 ResultStr += Context->getObjCClassType().getAsString(
1325 Context->getPrintingPolicy());
1326
1327 ResultStr += " self, ";
1328 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1329 ResultStr += " _cmd";
1330
1331 // Method arguments.
1332 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1333 E = OMD->param_end(); PI != E; ++PI) {
1334 ParmVarDecl *PDecl = *PI;
1335 ResultStr += ", ";
1336 if (PDecl->getType()->isObjCQualifiedIdType()) {
1337 ResultStr += "id ";
1338 ResultStr += PDecl->getNameAsString();
1339 } else {
1340 std::string Name = PDecl->getNameAsString();
1341 QualType QT = PDecl->getType();
1342 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001343 (void)convertBlockPointerToFunctionPointer(QT);
1344 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001345 ResultStr += Name;
1346 }
1347 }
1348 if (OMD->isVariadic())
1349 ResultStr += ", ...";
1350 ResultStr += ") ";
1351
1352 if (FPRetType) {
1353 ResultStr += ")"; // close the precedence "scope" for "*".
1354
1355 // Now, emit the argument types (if any).
1356 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1357 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001358 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001359 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001360 std::string ParamStr =
1361 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001362 ResultStr += ParamStr;
1363 }
1364 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001365 if (FT->getNumParams())
1366 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001367 ResultStr += "...";
1368 }
1369 ResultStr += ")";
1370 } else {
1371 ResultStr += "()";
1372 }
1373 }
1374}
1375void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1376 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1377 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1378
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001379 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001380 if (IMD->getIvarRBraceLoc().isValid()) {
1381 ReplaceText(IMD->getLocStart(), 1, "/** ");
1382 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001383 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001384 else {
1385 InsertText(IMD->getLocStart(), "// ");
1386 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001387 }
1388 else
1389 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001390
1391 for (ObjCCategoryImplDecl::instmeth_iterator
1392 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1393 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1394 I != E; ++I) {
1395 std::string ResultStr;
1396 ObjCMethodDecl *OMD = *I;
1397 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1398 SourceLocation LocStart = OMD->getLocStart();
1399 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1400
1401 const char *startBuf = SM->getCharacterData(LocStart);
1402 const char *endBuf = SM->getCharacterData(LocEnd);
1403 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1404 }
1405
1406 for (ObjCCategoryImplDecl::classmeth_iterator
1407 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1408 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1409 I != E; ++I) {
1410 std::string ResultStr;
1411 ObjCMethodDecl *OMD = *I;
1412 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1413 SourceLocation LocStart = OMD->getLocStart();
1414 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1415
1416 const char *startBuf = SM->getCharacterData(LocStart);
1417 const char *endBuf = SM->getCharacterData(LocEnd);
1418 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1419 }
1420 for (ObjCCategoryImplDecl::propimpl_iterator
1421 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1422 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1423 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001424 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001425 }
1426
1427 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1428}
1429
1430void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001431 // Do not synthesize more than once.
1432 if (ObjCSynthesizedStructs.count(ClassDecl))
1433 return;
1434 // Make sure super class's are written before current class is written.
1435 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1436 while (SuperClass) {
1437 RewriteInterfaceDecl(SuperClass);
1438 SuperClass = SuperClass->getSuperClass();
1439 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001440 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001441 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001442 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001443 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001444 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1445
Fariborz Jahanianff513382012-02-15 22:01:47 +00001446 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001447 // Mark this typedef as having been written into its c++ equivalent.
1448 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001449
1450 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001451 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001452 RewriteProperty(*I);
Fariborz Jahanianff513382012-02-15 22:01:47 +00001453 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001454 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001455 I != E; ++I)
1456 RewriteMethodDeclaration(*I);
1457 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001458 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001459 I != E; ++I)
1460 RewriteMethodDeclaration(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001461
Fariborz Jahanianff513382012-02-15 22:01:47 +00001462 // Lastly, comment out the @end.
1463 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001464 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001465 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001466}
1467
1468Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1469 SourceRange OldRange = PseudoOp->getSourceRange();
1470
1471 // We just magically know some things about the structure of this
1472 // expression.
1473 ObjCMessageExpr *OldMsg =
1474 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1475 PseudoOp->getNumSemanticExprs() - 1));
1476
1477 // Because the rewriter doesn't allow us to rewrite rewritten code,
1478 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001479 Expr *Base;
1480 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001481 {
1482 DisableReplaceStmtScope S(*this);
1483
1484 // Rebuild the base expression if we have one.
1485 Base = 0;
1486 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1487 Base = OldMsg->getInstanceReceiver();
1488 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1489 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1490 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001491
1492 unsigned numArgs = OldMsg->getNumArgs();
1493 for (unsigned i = 0; i < numArgs; i++) {
1494 Expr *Arg = OldMsg->getArg(i);
1495 if (isa<OpaqueValueExpr>(Arg))
1496 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1497 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1498 Args.push_back(Arg);
1499 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001500 }
1501
1502 // TODO: avoid this copy.
1503 SmallVector<SourceLocation, 1> SelLocs;
1504 OldMsg->getSelectorLocs(SelLocs);
1505
1506 ObjCMessageExpr *NewMsg = 0;
1507 switch (OldMsg->getReceiverKind()) {
1508 case ObjCMessageExpr::Class:
1509 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1510 OldMsg->getValueKind(),
1511 OldMsg->getLeftLoc(),
1512 OldMsg->getClassReceiverTypeInfo(),
1513 OldMsg->getSelector(),
1514 SelLocs,
1515 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001516 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001517 OldMsg->getRightLoc(),
1518 OldMsg->isImplicit());
1519 break;
1520
1521 case ObjCMessageExpr::Instance:
1522 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1523 OldMsg->getValueKind(),
1524 OldMsg->getLeftLoc(),
1525 Base,
1526 OldMsg->getSelector(),
1527 SelLocs,
1528 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001529 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001530 OldMsg->getRightLoc(),
1531 OldMsg->isImplicit());
1532 break;
1533
1534 case ObjCMessageExpr::SuperClass:
1535 case ObjCMessageExpr::SuperInstance:
1536 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1537 OldMsg->getValueKind(),
1538 OldMsg->getLeftLoc(),
1539 OldMsg->getSuperLoc(),
1540 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1541 OldMsg->getSuperType(),
1542 OldMsg->getSelector(),
1543 SelLocs,
1544 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001545 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001546 OldMsg->getRightLoc(),
1547 OldMsg->isImplicit());
1548 break;
1549 }
1550
1551 Stmt *Replacement = SynthMessageExpr(NewMsg);
1552 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1553 return Replacement;
1554}
1555
1556Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1557 SourceRange OldRange = PseudoOp->getSourceRange();
1558
1559 // We just magically know some things about the structure of this
1560 // expression.
1561 ObjCMessageExpr *OldMsg =
1562 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1563
1564 // Because the rewriter doesn't allow us to rewrite rewritten code,
1565 // we need to suppress rewriting the sub-statements.
1566 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001567 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001568 {
1569 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001570 // Rebuild the base expression if we have one.
1571 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1572 Base = OldMsg->getInstanceReceiver();
1573 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1574 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1575 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001576 unsigned numArgs = OldMsg->getNumArgs();
1577 for (unsigned i = 0; i < numArgs; i++) {
1578 Expr *Arg = OldMsg->getArg(i);
1579 if (isa<OpaqueValueExpr>(Arg))
1580 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1581 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1582 Args.push_back(Arg);
1583 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001584 }
1585
1586 // Intentionally empty.
1587 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001588
1589 ObjCMessageExpr *NewMsg = 0;
1590 switch (OldMsg->getReceiverKind()) {
1591 case ObjCMessageExpr::Class:
1592 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1593 OldMsg->getValueKind(),
1594 OldMsg->getLeftLoc(),
1595 OldMsg->getClassReceiverTypeInfo(),
1596 OldMsg->getSelector(),
1597 SelLocs,
1598 OldMsg->getMethodDecl(),
1599 Args,
1600 OldMsg->getRightLoc(),
1601 OldMsg->isImplicit());
1602 break;
1603
1604 case ObjCMessageExpr::Instance:
1605 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1606 OldMsg->getValueKind(),
1607 OldMsg->getLeftLoc(),
1608 Base,
1609 OldMsg->getSelector(),
1610 SelLocs,
1611 OldMsg->getMethodDecl(),
1612 Args,
1613 OldMsg->getRightLoc(),
1614 OldMsg->isImplicit());
1615 break;
1616
1617 case ObjCMessageExpr::SuperClass:
1618 case ObjCMessageExpr::SuperInstance:
1619 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1620 OldMsg->getValueKind(),
1621 OldMsg->getLeftLoc(),
1622 OldMsg->getSuperLoc(),
1623 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1624 OldMsg->getSuperType(),
1625 OldMsg->getSelector(),
1626 SelLocs,
1627 OldMsg->getMethodDecl(),
1628 Args,
1629 OldMsg->getRightLoc(),
1630 OldMsg->isImplicit());
1631 break;
1632 }
1633
1634 Stmt *Replacement = SynthMessageExpr(NewMsg);
1635 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1636 return Replacement;
1637}
1638
1639/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001640/// ((NSUInteger (*)
1641/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001642/// (void *)objc_msgSend)((id)l_collection,
1643/// sel_registerName(
1644/// "countByEnumeratingWithState:objects:count:"),
1645/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001646/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001647///
1648void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001649 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1650 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001651 buf += "\n\t\t";
1652 buf += "((id)l_collection,\n\t\t";
1653 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1654 buf += "\n\t\t";
1655 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001656 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001657}
1658
1659/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1660/// statement to exit to its outer synthesized loop.
1661///
1662Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1663 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1664 return S;
1665 // replace break with goto __break_label
1666 std::string buf;
1667
1668 SourceLocation startLoc = S->getLocStart();
1669 buf = "goto __break_label_";
1670 buf += utostr(ObjCBcLabelNo.back());
1671 ReplaceText(startLoc, strlen("break"), buf);
1672
1673 return 0;
1674}
1675
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001676void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1677 SourceLocation Loc,
1678 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001679 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001680 LineString += "\n#line ";
1681 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1682 LineString += utostr(PLoc.getLine());
1683 LineString += " \"";
1684 LineString += Lexer::Stringify(PLoc.getFilename());
1685 LineString += "\"\n";
1686 }
1687}
1688
Fariborz Jahanian11671902012-02-07 17:11:38 +00001689/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1690/// statement to continue with its inner synthesized loop.
1691///
1692Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1693 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1694 return S;
1695 // replace continue with goto __continue_label
1696 std::string buf;
1697
1698 SourceLocation startLoc = S->getLocStart();
1699 buf = "goto __continue_label_";
1700 buf += utostr(ObjCBcLabelNo.back());
1701 ReplaceText(startLoc, strlen("continue"), buf);
1702
1703 return 0;
1704}
1705
1706/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1707/// It rewrites:
1708/// for ( type elem in collection) { stmts; }
1709
1710/// Into:
1711/// {
1712/// type elem;
1713/// struct __objcFastEnumerationState enumState = { 0 };
1714/// id __rw_items[16];
1715/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001716/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001717/// objects:__rw_items count:16];
1718/// if (limit) {
1719/// unsigned long startMutations = *enumState.mutationsPtr;
1720/// do {
1721/// unsigned long counter = 0;
1722/// do {
1723/// if (startMutations != *enumState.mutationsPtr)
1724/// objc_enumerationMutation(l_collection);
1725/// elem = (type)enumState.itemsPtr[counter++];
1726/// stmts;
1727/// __continue_label: ;
1728/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001729/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1730/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001731/// elem = nil;
1732/// __break_label: ;
1733/// }
1734/// else
1735/// elem = nil;
1736/// }
1737///
1738Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1739 SourceLocation OrigEnd) {
1740 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1741 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1742 "ObjCForCollectionStmt Statement stack mismatch");
1743 assert(!ObjCBcLabelNo.empty() &&
1744 "ObjCForCollectionStmt - Label No stack empty");
1745
1746 SourceLocation startLoc = S->getLocStart();
1747 const char *startBuf = SM->getCharacterData(startLoc);
1748 StringRef elementName;
1749 std::string elementTypeAsString;
1750 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001751 // line directive first.
1752 SourceLocation ForEachLoc = S->getForLoc();
1753 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1754 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001755 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1756 // type elem;
1757 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1758 QualType ElementType = cast<ValueDecl>(D)->getType();
1759 if (ElementType->isObjCQualifiedIdType() ||
1760 ElementType->isObjCQualifiedInterfaceType())
1761 // Simply use 'id' for all qualified types.
1762 elementTypeAsString = "id";
1763 else
1764 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1765 buf += elementTypeAsString;
1766 buf += " ";
1767 elementName = D->getName();
1768 buf += elementName;
1769 buf += ";\n\t";
1770 }
1771 else {
1772 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1773 elementName = DR->getDecl()->getName();
1774 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1775 if (VD->getType()->isObjCQualifiedIdType() ||
1776 VD->getType()->isObjCQualifiedInterfaceType())
1777 // Simply use 'id' for all qualified types.
1778 elementTypeAsString = "id";
1779 else
1780 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1781 }
1782
1783 // struct __objcFastEnumerationState enumState = { 0 };
1784 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1785 // id __rw_items[16];
1786 buf += "id __rw_items[16];\n\t";
1787 // id l_collection = (id)
1788 buf += "id l_collection = (id)";
1789 // Find start location of 'collection' the hard way!
1790 const char *startCollectionBuf = startBuf;
1791 startCollectionBuf += 3; // skip 'for'
1792 startCollectionBuf = strchr(startCollectionBuf, '(');
1793 startCollectionBuf++; // skip '('
1794 // find 'in' and skip it.
1795 while (*startCollectionBuf != ' ' ||
1796 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1797 (*(startCollectionBuf+3) != ' ' &&
1798 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1799 startCollectionBuf++;
1800 startCollectionBuf += 3;
1801
1802 // Replace: "for (type element in" with string constructed thus far.
1803 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1804 // Replace ')' in for '(' type elem in collection ')' with ';'
1805 SourceLocation rightParenLoc = S->getRParenLoc();
1806 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1807 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1808 buf = ";\n\t";
1809
1810 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1811 // objects:__rw_items count:16];
1812 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001813 // NSUInteger limit =
1814 // ((NSUInteger (*)
1815 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001816 // (void *)objc_msgSend)((id)l_collection,
1817 // sel_registerName(
1818 // "countByEnumeratingWithState:objects:count:"),
1819 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001820 // (id *)__rw_items, (NSUInteger)16);
1821 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001822 SynthCountByEnumWithState(buf);
1823 buf += ";\n\t";
1824 /// if (limit) {
1825 /// unsigned long startMutations = *enumState.mutationsPtr;
1826 /// do {
1827 /// unsigned long counter = 0;
1828 /// do {
1829 /// if (startMutations != *enumState.mutationsPtr)
1830 /// objc_enumerationMutation(l_collection);
1831 /// elem = (type)enumState.itemsPtr[counter++];
1832 buf += "if (limit) {\n\t";
1833 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1834 buf += "do {\n\t\t";
1835 buf += "unsigned long counter = 0;\n\t\t";
1836 buf += "do {\n\t\t\t";
1837 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1838 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1839 buf += elementName;
1840 buf += " = (";
1841 buf += elementTypeAsString;
1842 buf += ")enumState.itemsPtr[counter++];";
1843 // Replace ')' in for '(' type elem in collection ')' with all of these.
1844 ReplaceText(lparenLoc, 1, buf);
1845
1846 /// __continue_label: ;
1847 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001848 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1849 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001850 /// elem = nil;
1851 /// __break_label: ;
1852 /// }
1853 /// else
1854 /// elem = nil;
1855 /// }
1856 ///
1857 buf = ";\n\t";
1858 buf += "__continue_label_";
1859 buf += utostr(ObjCBcLabelNo.back());
1860 buf += ": ;";
1861 buf += "\n\t\t";
1862 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001863 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001864 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001865 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001866 buf += elementName;
1867 buf += " = ((";
1868 buf += elementTypeAsString;
1869 buf += ")0);\n\t";
1870 buf += "__break_label_";
1871 buf += utostr(ObjCBcLabelNo.back());
1872 buf += ": ;\n\t";
1873 buf += "}\n\t";
1874 buf += "else\n\t\t";
1875 buf += elementName;
1876 buf += " = ((";
1877 buf += elementTypeAsString;
1878 buf += ")0);\n\t";
1879 buf += "}\n";
1880
1881 // Insert all these *after* the statement body.
1882 // FIXME: If this should support Obj-C++, support CXXTryStmt
1883 if (isa<CompoundStmt>(S->getBody())) {
1884 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1885 InsertText(endBodyLoc, buf);
1886 } else {
1887 /* Need to treat single statements specially. For example:
1888 *
1889 * for (A *a in b) if (stuff()) break;
1890 * for (A *a in b) xxxyy;
1891 *
1892 * The following code simply scans ahead to the semi to find the actual end.
1893 */
1894 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1895 const char *semiBuf = strchr(stmtBuf, ';');
1896 assert(semiBuf && "Can't find ';'");
1897 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1898 InsertText(endBodyLoc, buf);
1899 }
1900 Stmts.pop_back();
1901 ObjCBcLabelNo.pop_back();
1902 return 0;
1903}
1904
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001905static void Write_RethrowObject(std::string &buf) {
1906 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1907 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1908 buf += "\tid rethrow;\n";
1909 buf += "\t} _fin_force_rethow(_rethrow);";
1910}
1911
Fariborz Jahanian11671902012-02-07 17:11:38 +00001912/// RewriteObjCSynchronizedStmt -
1913/// This routine rewrites @synchronized(expr) stmt;
1914/// into:
1915/// objc_sync_enter(expr);
1916/// @try stmt @finally { objc_sync_exit(expr); }
1917///
1918Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1919 // Get the start location and compute the semi location.
1920 SourceLocation startLoc = S->getLocStart();
1921 const char *startBuf = SM->getCharacterData(startLoc);
1922
1923 assert((*startBuf == '@') && "bogus @synchronized location");
1924
1925 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001926 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1927 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001928 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001929
Fariborz Jahanian11671902012-02-07 17:11:38 +00001930 const char *lparenBuf = startBuf;
1931 while (*lparenBuf != '(') lparenBuf++;
1932 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001933
1934 buf = "; objc_sync_enter(_sync_obj);\n";
1935 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1936 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1937 buf += "\n\tid sync_exit;";
1938 buf += "\n\t} _sync_exit(_sync_obj);\n";
1939
1940 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1941 // the sync expression is typically a message expression that's already
1942 // been rewritten! (which implies the SourceLocation's are invalid).
1943 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1944 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1945 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1946 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1947
1948 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1949 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1950 assert (*LBraceLocBuf == '{');
1951 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001952
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001953 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001954 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1955 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001956
1957 buf = "} catch (id e) {_rethrow = e;}\n";
1958 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001959 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001960 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001961
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001962 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001963
Fariborz Jahanian11671902012-02-07 17:11:38 +00001964 return 0;
1965}
1966
1967void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1968{
1969 // Perform a bottom up traversal of all children.
1970 for (Stmt::child_range CI = S->children(); CI; ++CI)
1971 if (*CI)
1972 WarnAboutReturnGotoStmts(*CI);
1973
1974 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1975 Diags.Report(Context->getFullLoc(S->getLocStart()),
1976 TryFinallyContainsReturnDiag);
1977 }
1978 return;
1979}
1980
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001981Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1982 SourceLocation startLoc = S->getAtLoc();
1983 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001984 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1985 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001986
1987 return 0;
1988}
1989
Fariborz Jahanian11671902012-02-07 17:11:38 +00001990Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001991 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001992 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001993 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001994 SourceLocation TryLocation = S->getAtTryLoc();
1995 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001996
1997 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001998 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001999 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002000 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002001 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002002 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002003 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002004 // Get the start location and compute the semi location.
2005 SourceLocation startLoc = S->getLocStart();
2006 const char *startBuf = SM->getCharacterData(startLoc);
2007
2008 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002009 if (finalStmt)
2010 ReplaceText(startLoc, 1, buf);
2011 else
2012 // @try -> try
2013 ReplaceText(startLoc, 1, "");
2014
Fariborz Jahanian11671902012-02-07 17:11:38 +00002015 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2016 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002017 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002018
Fariborz Jahanian11671902012-02-07 17:11:38 +00002019 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002020 bool AtRemoved = false;
2021 if (catchDecl) {
2022 QualType t = catchDecl->getType();
2023 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2024 // Should be a pointer to a class.
2025 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2026 if (IDecl) {
2027 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002028 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2029
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002030 startBuf = SM->getCharacterData(startLoc);
2031 assert((*startBuf == '@') && "bogus @catch location");
2032 SourceLocation rParenLoc = Catch->getRParenLoc();
2033 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2034
2035 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002036 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002037 Result += " *_"; Result += catchDecl->getNameAsString();
2038 Result += ")";
2039 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2040 // Foo *e = (Foo *)_e;
2041 Result.clear();
2042 Result = "{ ";
2043 Result += IDecl->getNameAsString();
2044 Result += " *"; Result += catchDecl->getNameAsString();
2045 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2046 Result += "_"; Result += catchDecl->getNameAsString();
2047
2048 Result += "; ";
2049 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2050 ReplaceText(lBraceLoc, 1, Result);
2051 AtRemoved = true;
2052 }
2053 }
2054 }
2055 if (!AtRemoved)
2056 // @catch -> catch
2057 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002058
Fariborz Jahanian11671902012-02-07 17:11:38 +00002059 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002060 if (finalStmt) {
2061 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002062 SourceLocation FinallyLoc = finalStmt->getLocStart();
2063
2064 if (noCatch) {
2065 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2066 buf += "catch (id e) {_rethrow = e;}\n";
2067 }
2068 else {
2069 buf += "}\n";
2070 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2071 buf += "catch (id e) {_rethrow = e;}\n";
2072 }
2073
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002074 SourceLocation startFinalLoc = finalStmt->getLocStart();
2075 ReplaceText(startFinalLoc, 8, buf);
2076 Stmt *body = finalStmt->getFinallyBody();
2077 SourceLocation startFinalBodyLoc = body->getLocStart();
2078 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002079 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002080 ReplaceText(startFinalBodyLoc, 1, buf);
2081
2082 SourceLocation endFinalBodyLoc = body->getLocEnd();
2083 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002084 // Now check for any return/continue/go statements within the @try.
2085 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002086 }
2087
Fariborz Jahanian11671902012-02-07 17:11:38 +00002088 return 0;
2089}
2090
2091// This can't be done with ReplaceStmt(S, ThrowExpr), since
2092// the throw expression is typically a message expression that's already
2093// been rewritten! (which implies the SourceLocation's are invalid).
2094Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2095 // Get the start location and compute the semi location.
2096 SourceLocation startLoc = S->getLocStart();
2097 const char *startBuf = SM->getCharacterData(startLoc);
2098
2099 assert((*startBuf == '@') && "bogus @throw location");
2100
2101 std::string buf;
2102 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2103 if (S->getThrowExpr())
2104 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002105 else
2106 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002107
2108 // handle "@ throw" correctly.
2109 const char *wBuf = strchr(startBuf, 'w');
2110 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2111 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2112
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002113 SourceLocation endLoc = S->getLocEnd();
2114 const char *endBuf = SM->getCharacterData(endLoc);
2115 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002116 assert((*semiBuf == ';') && "@throw: can't find ';'");
2117 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002118 if (S->getThrowExpr())
2119 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002120 return 0;
2121}
2122
2123Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2124 // Create a new string expression.
2125 QualType StrType = Context->getPointerType(Context->CharTy);
2126 std::string StrEncoding;
2127 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2128 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2129 StringLiteral::Ascii, false,
2130 StrType, SourceLocation());
2131 ReplaceStmt(Exp, Replacement);
2132
2133 // Replace this subexpr in the parent.
2134 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2135 return Replacement;
2136}
2137
2138Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2139 if (!SelGetUidFunctionDecl)
2140 SynthSelGetUidFunctionDecl();
2141 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2142 // Create a call to sel_registerName("selName").
2143 SmallVector<Expr*, 8> SelExprs;
2144 QualType argType = Context->getPointerType(Context->CharTy);
2145 SelExprs.push_back(StringLiteral::Create(*Context,
2146 Exp->getSelector().getAsString(),
2147 StringLiteral::Ascii, false,
2148 argType, SourceLocation()));
2149 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2150 &SelExprs[0], SelExprs.size());
2151 ReplaceStmt(Exp, SelExp);
2152 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2153 return SelExp;
2154}
2155
2156CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2157 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2158 SourceLocation EndLoc) {
2159 // Get the type, we will need to reference it in a couple spots.
2160 QualType msgSendType = FD->getType();
2161
2162 // Create a reference to the objc_msgSend() declaration.
2163 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002164 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002165
2166 // Now, we cast the reference to a pointer to the objc_msgSend type.
2167 QualType pToFunc = Context->getPointerType(msgSendType);
2168 ImplicitCastExpr *ICE =
2169 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2170 DRE, 0, VK_RValue);
2171
2172 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2173
2174 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002175 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002176 FT->getCallResultType(*Context),
2177 VK_RValue, EndLoc);
2178 return Exp;
2179}
2180
2181static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2182 const char *&startRef, const char *&endRef) {
2183 while (startBuf < endBuf) {
2184 if (*startBuf == '<')
2185 startRef = startBuf; // mark the start.
2186 if (*startBuf == '>') {
2187 if (startRef && *startRef == '<') {
2188 endRef = startBuf; // mark the end.
2189 return true;
2190 }
2191 return false;
2192 }
2193 startBuf++;
2194 }
2195 return false;
2196}
2197
2198static void scanToNextArgument(const char *&argRef) {
2199 int angle = 0;
2200 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2201 if (*argRef == '<')
2202 angle++;
2203 else if (*argRef == '>')
2204 angle--;
2205 argRef++;
2206 }
2207 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2208}
2209
2210bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2211 if (T->isObjCQualifiedIdType())
2212 return true;
2213 if (const PointerType *PT = T->getAs<PointerType>()) {
2214 if (PT->getPointeeType()->isObjCQualifiedIdType())
2215 return true;
2216 }
2217 if (T->isObjCObjectPointerType()) {
2218 T = T->getPointeeType();
2219 return T->isObjCQualifiedInterfaceType();
2220 }
2221 if (T->isArrayType()) {
2222 QualType ElemTy = Context->getBaseElementType(T);
2223 return needToScanForQualifiers(ElemTy);
2224 }
2225 return false;
2226}
2227
2228void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2229 QualType Type = E->getType();
2230 if (needToScanForQualifiers(Type)) {
2231 SourceLocation Loc, EndLoc;
2232
2233 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2234 Loc = ECE->getLParenLoc();
2235 EndLoc = ECE->getRParenLoc();
2236 } else {
2237 Loc = E->getLocStart();
2238 EndLoc = E->getLocEnd();
2239 }
2240 // This will defend against trying to rewrite synthesized expressions.
2241 if (Loc.isInvalid() || EndLoc.isInvalid())
2242 return;
2243
2244 const char *startBuf = SM->getCharacterData(Loc);
2245 const char *endBuf = SM->getCharacterData(EndLoc);
2246 const char *startRef = 0, *endRef = 0;
2247 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2248 // Get the locations of the startRef, endRef.
2249 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2250 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2251 // Comment out the protocol references.
2252 InsertText(LessLoc, "/*");
2253 InsertText(GreaterLoc, "*/");
2254 }
2255 }
2256}
2257
2258void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2259 SourceLocation Loc;
2260 QualType Type;
2261 const FunctionProtoType *proto = 0;
2262 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2263 Loc = VD->getLocation();
2264 Type = VD->getType();
2265 }
2266 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2267 Loc = FD->getLocation();
2268 // Check for ObjC 'id' and class types that have been adorned with protocol
2269 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2270 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2271 assert(funcType && "missing function type");
2272 proto = dyn_cast<FunctionProtoType>(funcType);
2273 if (!proto)
2274 return;
Alp Toker314cc812014-01-25 16:55:45 +00002275 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002276 }
2277 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2278 Loc = FD->getLocation();
2279 Type = FD->getType();
2280 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002281 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2282 Loc = TD->getLocation();
2283 Type = TD->getUnderlyingType();
2284 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002285 else
2286 return;
2287
2288 if (needToScanForQualifiers(Type)) {
2289 // Since types are unique, we need to scan the buffer.
2290
2291 const char *endBuf = SM->getCharacterData(Loc);
2292 const char *startBuf = endBuf;
2293 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2294 startBuf--; // scan backward (from the decl location) for return type.
2295 const char *startRef = 0, *endRef = 0;
2296 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2297 // Get the locations of the startRef, endRef.
2298 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2299 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2300 // Comment out the protocol references.
2301 InsertText(LessLoc, "/*");
2302 InsertText(GreaterLoc, "*/");
2303 }
2304 }
2305 if (!proto)
2306 return; // most likely, was a variable
2307 // Now check arguments.
2308 const char *startBuf = SM->getCharacterData(Loc);
2309 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002310 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2311 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002312 // Since types are unique, we need to scan the buffer.
2313
2314 const char *endBuf = startBuf;
2315 // scan forward (from the decl location) for argument types.
2316 scanToNextArgument(endBuf);
2317 const char *startRef = 0, *endRef = 0;
2318 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2319 // Get the locations of the startRef, endRef.
2320 SourceLocation LessLoc =
2321 Loc.getLocWithOffset(startRef-startFuncBuf);
2322 SourceLocation GreaterLoc =
2323 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2324 // Comment out the protocol references.
2325 InsertText(LessLoc, "/*");
2326 InsertText(GreaterLoc, "*/");
2327 }
2328 startBuf = ++endBuf;
2329 }
2330 else {
2331 // If the function name is derived from a macro expansion, then the
2332 // argument buffer will not follow the name. Need to speak with Chris.
2333 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2334 startBuf++; // scan forward (from the decl location) for argument types.
2335 startBuf++;
2336 }
2337 }
2338}
2339
2340void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2341 QualType QT = ND->getType();
2342 const Type* TypePtr = QT->getAs<Type>();
2343 if (!isa<TypeOfExprType>(TypePtr))
2344 return;
2345 while (isa<TypeOfExprType>(TypePtr)) {
2346 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2347 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2348 TypePtr = QT->getAs<Type>();
2349 }
2350 // FIXME. This will not work for multiple declarators; as in:
2351 // __typeof__(a) b,c,d;
2352 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2353 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2354 const char *startBuf = SM->getCharacterData(DeclLoc);
2355 if (ND->getInit()) {
2356 std::string Name(ND->getNameAsString());
2357 TypeAsString += " " + Name + " = ";
2358 Expr *E = ND->getInit();
2359 SourceLocation startLoc;
2360 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2361 startLoc = ECE->getLParenLoc();
2362 else
2363 startLoc = E->getLocStart();
2364 startLoc = SM->getExpansionLoc(startLoc);
2365 const char *endBuf = SM->getCharacterData(startLoc);
2366 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2367 }
2368 else {
2369 SourceLocation X = ND->getLocEnd();
2370 X = SM->getExpansionLoc(X);
2371 const char *endBuf = SM->getCharacterData(X);
2372 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2373 }
2374}
2375
2376// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2377void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2378 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2379 SmallVector<QualType, 16> ArgTys;
2380 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2381 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002382 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002383 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002384 SourceLocation(),
2385 SourceLocation(),
2386 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002387 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002388}
2389
2390void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2391 // declared in <objc/objc.h>
2392 if (FD->getIdentifier() &&
2393 FD->getName() == "sel_registerName") {
2394 SelGetUidFunctionDecl = FD;
2395 return;
2396 }
2397 RewriteObjCQualifiedInterfaceTypes(FD);
2398}
2399
2400void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2401 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2402 const char *argPtr = TypeString.c_str();
2403 if (!strchr(argPtr, '^')) {
2404 Str += TypeString;
2405 return;
2406 }
2407 while (*argPtr) {
2408 Str += (*argPtr == '^' ? '*' : *argPtr);
2409 argPtr++;
2410 }
2411}
2412
2413// FIXME. Consolidate this routine with RewriteBlockPointerType.
2414void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2415 ValueDecl *VD) {
2416 QualType Type = VD->getType();
2417 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2418 const char *argPtr = TypeString.c_str();
2419 int paren = 0;
2420 while (*argPtr) {
2421 switch (*argPtr) {
2422 case '(':
2423 Str += *argPtr;
2424 paren++;
2425 break;
2426 case ')':
2427 Str += *argPtr;
2428 paren--;
2429 break;
2430 case '^':
2431 Str += '*';
2432 if (paren == 1)
2433 Str += VD->getNameAsString();
2434 break;
2435 default:
2436 Str += *argPtr;
2437 break;
2438 }
2439 argPtr++;
2440 }
2441}
2442
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002443void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2444 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2445 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2446 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2447 if (!proto)
2448 return;
Alp Toker314cc812014-01-25 16:55:45 +00002449 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002450 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2451 FdStr += " ";
2452 FdStr += FD->getName();
2453 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002454 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002455 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002456 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002457 RewriteBlockPointerType(FdStr, ArgType);
2458 if (i+1 < numArgs)
2459 FdStr += ", ";
2460 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002461 if (FD->isVariadic()) {
2462 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2463 }
2464 else
2465 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002466 InsertText(FunLocStart, FdStr);
2467}
2468
Benjamin Kramer60509af2013-09-09 14:48:42 +00002469// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2470void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2471 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002472 return;
2473 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2474 SmallVector<QualType, 16> ArgTys;
2475 QualType argT = Context->getObjCIdType();
2476 assert(!argT.isNull() && "Can't find 'id' type");
2477 ArgTys.push_back(argT);
2478 ArgTys.push_back(argT);
2479 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002480 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002481 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002482 SourceLocation(),
2483 SourceLocation(),
2484 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002485 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002486}
2487
2488// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2489void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2490 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2491 SmallVector<QualType, 16> ArgTys;
2492 QualType argT = Context->getObjCIdType();
2493 assert(!argT.isNull() && "Can't find 'id' type");
2494 ArgTys.push_back(argT);
2495 argT = Context->getObjCSelType();
2496 assert(!argT.isNull() && "Can't find 'SEL' type");
2497 ArgTys.push_back(argT);
2498 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002499 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002500 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002501 SourceLocation(),
2502 SourceLocation(),
2503 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002504 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002505}
2506
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002507// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002508void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2509 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002510 SmallVector<QualType, 2> ArgTys;
2511 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002512 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002513 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002514 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002515 SourceLocation(),
2516 SourceLocation(),
2517 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002518 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002519}
2520
2521// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2522void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2523 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2524 SmallVector<QualType, 16> ArgTys;
2525 QualType argT = Context->getObjCIdType();
2526 assert(!argT.isNull() && "Can't find 'id' type");
2527 ArgTys.push_back(argT);
2528 argT = Context->getObjCSelType();
2529 assert(!argT.isNull() && "Can't find 'SEL' type");
2530 ArgTys.push_back(argT);
2531 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002532 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002533 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002534 SourceLocation(),
2535 SourceLocation(),
2536 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002537 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002538}
2539
2540// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002541// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002542void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2543 IdentifierInfo *msgSendIdent =
2544 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002545 SmallVector<QualType, 2> ArgTys;
2546 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002547 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002548 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002549 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2550 SourceLocation(),
2551 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002552 msgSendIdent,
2553 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002554 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002555}
2556
2557// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2558void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2559 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2560 SmallVector<QualType, 16> ArgTys;
2561 QualType argT = Context->getObjCIdType();
2562 assert(!argT.isNull() && "Can't find 'id' type");
2563 ArgTys.push_back(argT);
2564 argT = Context->getObjCSelType();
2565 assert(!argT.isNull() && "Can't find 'SEL' type");
2566 ArgTys.push_back(argT);
2567 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002568 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002569 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002570 SourceLocation(),
2571 SourceLocation(),
2572 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002573 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002574}
2575
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002576// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002577void RewriteModernObjC::SynthGetClassFunctionDecl() {
2578 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2579 SmallVector<QualType, 16> ArgTys;
2580 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002581 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002582 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002583 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002584 SourceLocation(),
2585 SourceLocation(),
2586 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002587 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002588}
2589
2590// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2591void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2592 IdentifierInfo *getSuperClassIdent =
2593 &Context->Idents.get("class_getSuperclass");
2594 SmallVector<QualType, 16> ArgTys;
2595 ArgTys.push_back(Context->getObjCClassType());
2596 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002597 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002598 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2599 SourceLocation(),
2600 SourceLocation(),
2601 getSuperClassIdent,
2602 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002603 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002604}
2605
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002606// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002607void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2608 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2609 SmallVector<QualType, 16> ArgTys;
2610 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002611 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002612 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002613 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002614 SourceLocation(),
2615 SourceLocation(),
2616 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002617 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002618}
2619
2620Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2621 QualType strType = getConstantStringStructType();
2622
2623 std::string S = "__NSConstantStringImpl_";
2624
2625 std::string tmpName = InFileName;
2626 unsigned i;
2627 for (i=0; i < tmpName.length(); i++) {
2628 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002629 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002630 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002631 tmpName[i] = '_';
2632 }
2633 S += tmpName;
2634 S += "_";
2635 S += utostr(NumObjCStringLiterals++);
2636
2637 Preamble += "static __NSConstantStringImpl " + S;
2638 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2639 Preamble += "0x000007c8,"; // utf8_str
2640 // The pretty printer for StringLiteral handles escape characters properly.
2641 std::string prettyBufS;
2642 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002643 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002644 Preamble += prettyBuf.str();
2645 Preamble += ",";
2646 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2647
2648 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2649 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002650 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002651 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002652 SourceLocation());
2653 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2654 Context->getPointerType(DRE->getType()),
2655 VK_RValue, OK_Ordinary,
2656 SourceLocation());
2657 // cast to NSConstantString *
2658 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2659 CK_CPointerToObjCPointerCast, Unop);
2660 ReplaceStmt(Exp, cast);
2661 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2662 return cast;
2663}
2664
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002665Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2666 unsigned IntSize =
2667 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2668
2669 Expr *FlagExp = IntegerLiteral::Create(*Context,
2670 llvm::APInt(IntSize, Exp->getValue()),
2671 Context->IntTy, Exp->getLocation());
2672 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2673 CK_BitCast, FlagExp);
2674 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2675 cast);
2676 ReplaceStmt(Exp, PE);
2677 return PE;
2678}
2679
Patrick Beard0caa3942012-04-19 00:25:12 +00002680Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002681 // synthesize declaration of helper functions needed in this routine.
2682 if (!SelGetUidFunctionDecl)
2683 SynthSelGetUidFunctionDecl();
2684 // use objc_msgSend() for all.
2685 if (!MsgSendFunctionDecl)
2686 SynthMsgSendFunctionDecl();
2687 if (!GetClassFunctionDecl)
2688 SynthGetClassFunctionDecl();
2689
2690 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2691 SourceLocation StartLoc = Exp->getLocStart();
2692 SourceLocation EndLoc = Exp->getLocEnd();
2693
2694 // Synthesize a call to objc_msgSend().
2695 SmallVector<Expr*, 4> MsgExprs;
2696 SmallVector<Expr*, 4> ClsExprs;
2697 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002698
Patrick Beard0caa3942012-04-19 00:25:12 +00002699 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2700 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2701 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002702
Patrick Beard0caa3942012-04-19 00:25:12 +00002703 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002704 ClsExprs.push_back(StringLiteral::Create(*Context,
2705 clsName->getName(),
2706 StringLiteral::Ascii, false,
2707 argType, SourceLocation()));
2708 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2709 &ClsExprs[0],
2710 ClsExprs.size(),
2711 StartLoc, EndLoc);
2712 MsgExprs.push_back(Cls);
2713
Patrick Beard0caa3942012-04-19 00:25:12 +00002714 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002715 // it will be the 2nd argument.
2716 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002717 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002718 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002719 StringLiteral::Ascii, false,
2720 argType, SourceLocation()));
2721 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2722 &SelExprs[0], SelExprs.size(),
2723 StartLoc, EndLoc);
2724 MsgExprs.push_back(SelExp);
2725
Patrick Beard0caa3942012-04-19 00:25:12 +00002726 // User provided sub-expression is the 3rd, and last, argument.
2727 Expr *subExpr = Exp->getSubExpr();
2728 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002729 QualType type = ICE->getType();
2730 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2731 CastKind CK = CK_BitCast;
2732 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2733 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002734 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002735 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002736 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002737
2738 SmallVector<QualType, 4> ArgTypes;
2739 ArgTypes.push_back(Context->getObjCIdType());
2740 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002741 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2742 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002743 ArgTypes.push_back((*PI)->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002744
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002745 QualType returnType = Exp->getType();
2746 // Get the type, we will need to reference it in a couple spots.
2747 QualType msgSendType = MsgSendFlavor->getType();
2748
2749 // Create a reference to the objc_msgSend() declaration.
2750 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2751 VK_LValue, SourceLocation());
2752
2753 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002754 Context->getPointerType(Context->VoidTy),
2755 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002756
2757 // Now do the "normal" pointer to function cast.
2758 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002759 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002760 castType = Context->getPointerType(castType);
2761 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2762 cast);
2763
2764 // Don't forget the parens to enforce the proper binding.
2765 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2766
2767 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002768 CallExpr *CE = new (Context)
2769 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002770 ReplaceStmt(Exp, CE);
2771 return CE;
2772}
2773
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002774Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2775 // synthesize declaration of helper functions needed in this routine.
2776 if (!SelGetUidFunctionDecl)
2777 SynthSelGetUidFunctionDecl();
2778 // use objc_msgSend() for all.
2779 if (!MsgSendFunctionDecl)
2780 SynthMsgSendFunctionDecl();
2781 if (!GetClassFunctionDecl)
2782 SynthGetClassFunctionDecl();
2783
2784 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2785 SourceLocation StartLoc = Exp->getLocStart();
2786 SourceLocation EndLoc = Exp->getLocEnd();
2787
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002788 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002789 QualType IntQT = Context->IntTy;
2790 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002791 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002792 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002793 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2794 DeclRefExpr *NSArrayDRE =
2795 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2796 SourceLocation());
2797
2798 SmallVector<Expr*, 16> InitExprs;
2799 unsigned NumElements = Exp->getNumElements();
2800 unsigned UnsignedIntSize =
2801 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2802 Expr *count = IntegerLiteral::Create(*Context,
2803 llvm::APInt(UnsignedIntSize, NumElements),
2804 Context->UnsignedIntTy, SourceLocation());
2805 InitExprs.push_back(count);
2806 for (unsigned i = 0; i < NumElements; i++)
2807 InitExprs.push_back(Exp->getElement(i));
2808 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002809 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002810 NSArrayFType, VK_LValue, SourceLocation());
2811
2812 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2813 SourceLocation(),
2814 &Context->Idents.get("arr"),
2815 Context->getPointerType(Context->VoidPtrTy), 0,
2816 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002817 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002818 MemberExpr *ArrayLiteralME =
2819 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2820 SourceLocation(),
2821 ARRFD->getType(), VK_LValue,
2822 OK_Ordinary);
2823 QualType ConstIdT = Context->getObjCIdType().withConst();
2824 CStyleCastExpr * ArrayLiteralObjects =
2825 NoTypeInfoCStyleCastExpr(Context,
2826 Context->getPointerType(ConstIdT),
2827 CK_BitCast,
2828 ArrayLiteralME);
2829
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002830 // Synthesize a call to objc_msgSend().
2831 SmallVector<Expr*, 32> MsgExprs;
2832 SmallVector<Expr*, 4> ClsExprs;
2833 QualType argType = Context->getPointerType(Context->CharTy);
2834 QualType expType = Exp->getType();
2835
2836 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2837 ObjCInterfaceDecl *Class =
2838 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2839
2840 IdentifierInfo *clsName = Class->getIdentifier();
2841 ClsExprs.push_back(StringLiteral::Create(*Context,
2842 clsName->getName(),
2843 StringLiteral::Ascii, false,
2844 argType, SourceLocation()));
2845 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2846 &ClsExprs[0],
2847 ClsExprs.size(),
2848 StartLoc, EndLoc);
2849 MsgExprs.push_back(Cls);
2850
2851 // Create a call to sel_registerName("arrayWithObjects:count:").
2852 // it will be the 2nd argument.
2853 SmallVector<Expr*, 4> SelExprs;
2854 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2855 SelExprs.push_back(StringLiteral::Create(*Context,
2856 ArrayMethod->getSelector().getAsString(),
2857 StringLiteral::Ascii, false,
2858 argType, SourceLocation()));
2859 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2860 &SelExprs[0], SelExprs.size(),
2861 StartLoc, EndLoc);
2862 MsgExprs.push_back(SelExp);
2863
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002864 // (const id [])objects
2865 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002866
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002867 // (NSUInteger)cnt
2868 Expr *cnt = IntegerLiteral::Create(*Context,
2869 llvm::APInt(UnsignedIntSize, NumElements),
2870 Context->UnsignedIntTy, SourceLocation());
2871 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002872
2873
2874 SmallVector<QualType, 4> ArgTypes;
2875 ArgTypes.push_back(Context->getObjCIdType());
2876 ArgTypes.push_back(Context->getObjCSelType());
2877 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2878 E = ArrayMethod->param_end(); PI != E; ++PI)
2879 ArgTypes.push_back((*PI)->getType());
2880
2881 QualType returnType = Exp->getType();
2882 // Get the type, we will need to reference it in a couple spots.
2883 QualType msgSendType = MsgSendFlavor->getType();
2884
2885 // Create a reference to the objc_msgSend() declaration.
2886 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2887 VK_LValue, SourceLocation());
2888
2889 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2890 Context->getPointerType(Context->VoidTy),
2891 CK_BitCast, DRE);
2892
2893 // Now do the "normal" pointer to function cast.
2894 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002895 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002896 castType = Context->getPointerType(castType);
2897 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2898 cast);
2899
2900 // Don't forget the parens to enforce the proper binding.
2901 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2902
2903 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002904 CallExpr *CE = new (Context)
2905 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002906 ReplaceStmt(Exp, CE);
2907 return CE;
2908}
2909
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002910Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2911 // synthesize declaration of helper functions needed in this routine.
2912 if (!SelGetUidFunctionDecl)
2913 SynthSelGetUidFunctionDecl();
2914 // use objc_msgSend() for all.
2915 if (!MsgSendFunctionDecl)
2916 SynthMsgSendFunctionDecl();
2917 if (!GetClassFunctionDecl)
2918 SynthGetClassFunctionDecl();
2919
2920 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2921 SourceLocation StartLoc = Exp->getLocStart();
2922 SourceLocation EndLoc = Exp->getLocEnd();
2923
2924 // Build the expression: __NSContainer_literal(int, ...).arr
2925 QualType IntQT = Context->IntTy;
2926 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002927 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002928 std::string NSDictFName("__NSContainer_literal");
2929 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2930 DeclRefExpr *NSDictDRE =
2931 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2932 SourceLocation());
2933
2934 SmallVector<Expr*, 16> KeyExprs;
2935 SmallVector<Expr*, 16> ValueExprs;
2936
2937 unsigned NumElements = Exp->getNumElements();
2938 unsigned UnsignedIntSize =
2939 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2940 Expr *count = IntegerLiteral::Create(*Context,
2941 llvm::APInt(UnsignedIntSize, NumElements),
2942 Context->UnsignedIntTy, SourceLocation());
2943 KeyExprs.push_back(count);
2944 ValueExprs.push_back(count);
2945 for (unsigned i = 0; i < NumElements; i++) {
2946 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2947 KeyExprs.push_back(Element.Key);
2948 ValueExprs.push_back(Element.Value);
2949 }
2950
2951 // (const id [])objects
2952 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002953 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002954 NSDictFType, VK_LValue, SourceLocation());
2955
2956 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2957 SourceLocation(),
2958 &Context->Idents.get("arr"),
2959 Context->getPointerType(Context->VoidPtrTy), 0,
2960 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002961 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002962 MemberExpr *DictLiteralValueME =
2963 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2964 SourceLocation(),
2965 ARRFD->getType(), VK_LValue,
2966 OK_Ordinary);
2967 QualType ConstIdT = Context->getObjCIdType().withConst();
2968 CStyleCastExpr * DictValueObjects =
2969 NoTypeInfoCStyleCastExpr(Context,
2970 Context->getPointerType(ConstIdT),
2971 CK_BitCast,
2972 DictLiteralValueME);
2973 // (const id <NSCopying> [])keys
2974 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002975 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002976 NSDictFType, VK_LValue, SourceLocation());
2977
2978 MemberExpr *DictLiteralKeyME =
2979 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2980 SourceLocation(),
2981 ARRFD->getType(), VK_LValue,
2982 OK_Ordinary);
2983
2984 CStyleCastExpr * DictKeyObjects =
2985 NoTypeInfoCStyleCastExpr(Context,
2986 Context->getPointerType(ConstIdT),
2987 CK_BitCast,
2988 DictLiteralKeyME);
2989
2990
2991
2992 // Synthesize a call to objc_msgSend().
2993 SmallVector<Expr*, 32> MsgExprs;
2994 SmallVector<Expr*, 4> ClsExprs;
2995 QualType argType = Context->getPointerType(Context->CharTy);
2996 QualType expType = Exp->getType();
2997
2998 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2999 ObjCInterfaceDecl *Class =
3000 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
3001
3002 IdentifierInfo *clsName = Class->getIdentifier();
3003 ClsExprs.push_back(StringLiteral::Create(*Context,
3004 clsName->getName(),
3005 StringLiteral::Ascii, false,
3006 argType, SourceLocation()));
3007 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3008 &ClsExprs[0],
3009 ClsExprs.size(),
3010 StartLoc, EndLoc);
3011 MsgExprs.push_back(Cls);
3012
3013 // Create a call to sel_registerName("arrayWithObjects:count:").
3014 // it will be the 2nd argument.
3015 SmallVector<Expr*, 4> SelExprs;
3016 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
3017 SelExprs.push_back(StringLiteral::Create(*Context,
3018 DictMethod->getSelector().getAsString(),
3019 StringLiteral::Ascii, false,
3020 argType, SourceLocation()));
3021 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3022 &SelExprs[0], SelExprs.size(),
3023 StartLoc, EndLoc);
3024 MsgExprs.push_back(SelExp);
3025
3026 // (const id [])objects
3027 MsgExprs.push_back(DictValueObjects);
3028
3029 // (const id <NSCopying> [])keys
3030 MsgExprs.push_back(DictKeyObjects);
3031
3032 // (NSUInteger)cnt
3033 Expr *cnt = IntegerLiteral::Create(*Context,
3034 llvm::APInt(UnsignedIntSize, NumElements),
3035 Context->UnsignedIntTy, SourceLocation());
3036 MsgExprs.push_back(cnt);
3037
3038
3039 SmallVector<QualType, 8> ArgTypes;
3040 ArgTypes.push_back(Context->getObjCIdType());
3041 ArgTypes.push_back(Context->getObjCSelType());
3042 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3043 E = DictMethod->param_end(); PI != E; ++PI) {
3044 QualType T = (*PI)->getType();
3045 if (const PointerType* PT = T->getAs<PointerType>()) {
3046 QualType PointeeTy = PT->getPointeeType();
3047 convertToUnqualifiedObjCType(PointeeTy);
3048 T = Context->getPointerType(PointeeTy);
3049 }
3050 ArgTypes.push_back(T);
3051 }
3052
3053 QualType returnType = Exp->getType();
3054 // Get the type, we will need to reference it in a couple spots.
3055 QualType msgSendType = MsgSendFlavor->getType();
3056
3057 // Create a reference to the objc_msgSend() declaration.
3058 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3059 VK_LValue, SourceLocation());
3060
3061 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3062 Context->getPointerType(Context->VoidTy),
3063 CK_BitCast, DRE);
3064
3065 // Now do the "normal" pointer to function cast.
3066 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003067 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003068 castType = Context->getPointerType(castType);
3069 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3070 cast);
3071
3072 // Don't forget the parens to enforce the proper binding.
3073 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3074
3075 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003076 CallExpr *CE = new (Context)
3077 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003078 ReplaceStmt(Exp, CE);
3079 return CE;
3080}
3081
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003082// struct __rw_objc_super {
3083// struct objc_object *object; struct objc_object *superClass;
3084// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003085QualType RewriteModernObjC::getSuperStructType() {
3086 if (!SuperStructDecl) {
3087 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3088 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003089 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003090 QualType FieldTypes[2];
3091
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003092 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003093 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003094 // struct objc_object *superClass;
3095 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003096
3097 // Create fields
3098 for (unsigned i = 0; i < 2; ++i) {
3099 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3100 SourceLocation(),
3101 SourceLocation(), 0,
3102 FieldTypes[i], 0,
3103 /*BitWidth=*/0,
3104 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003105 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003106 }
3107
3108 SuperStructDecl->completeDefinition();
3109 }
3110 return Context->getTagDeclType(SuperStructDecl);
3111}
3112
3113QualType RewriteModernObjC::getConstantStringStructType() {
3114 if (!ConstantStringDecl) {
3115 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3116 SourceLocation(), SourceLocation(),
3117 &Context->Idents.get("__NSConstantStringImpl"));
3118 QualType FieldTypes[4];
3119
3120 // struct objc_object *receiver;
3121 FieldTypes[0] = Context->getObjCIdType();
3122 // int flags;
3123 FieldTypes[1] = Context->IntTy;
3124 // char *str;
3125 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3126 // long length;
3127 FieldTypes[3] = Context->LongTy;
3128
3129 // Create fields
3130 for (unsigned i = 0; i < 4; ++i) {
3131 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3132 ConstantStringDecl,
3133 SourceLocation(),
3134 SourceLocation(), 0,
3135 FieldTypes[i], 0,
3136 /*BitWidth=*/0,
3137 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003138 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003139 }
3140
3141 ConstantStringDecl->completeDefinition();
3142 }
3143 return Context->getTagDeclType(ConstantStringDecl);
3144}
3145
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003146/// getFunctionSourceLocation - returns start location of a function
3147/// definition. Complication arises when function has declared as
3148/// extern "C" or extern "C" {...}
3149static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3150 FunctionDecl *FD) {
3151 if (FD->isExternC() && !FD->isMain()) {
3152 const DeclContext *DC = FD->getDeclContext();
3153 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3154 // if it is extern "C" {...}, return function decl's own location.
3155 if (!LSD->getRBraceLoc().isValid())
3156 return LSD->getExternLoc();
3157 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003158 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003159 R.RewriteBlockLiteralFunctionDecl(FD);
3160 return FD->getTypeSpecStartLoc();
3161}
3162
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003163void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3164
3165 SourceLocation Location = D->getLocation();
3166
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003167 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003168 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003169 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3170 LineString += utostr(PLoc.getLine());
3171 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003172 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003173 if (isa<ObjCMethodDecl>(D))
3174 LineString += "\"";
3175 else LineString += "\"\n";
3176
3177 Location = D->getLocStart();
3178 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3179 if (FD->isExternC() && !FD->isMain()) {
3180 const DeclContext *DC = FD->getDeclContext();
3181 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3182 // if it is extern "C" {...}, return function decl's own location.
3183 if (!LSD->getRBraceLoc().isValid())
3184 Location = LSD->getExternLoc();
3185 }
3186 }
3187 InsertText(Location, LineString);
3188 }
3189}
3190
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003191/// SynthMsgSendStretCallExpr - This routine translates message expression
3192/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3193/// nil check on receiver must be performed before calling objc_msgSend_stret.
3194/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3195/// msgSendType - function type of objc_msgSend_stret(...)
3196/// returnType - Result type of the method being synthesized.
3197/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3198/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3199/// starting with receiver.
3200/// Method - Method being rewritten.
3201Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003202 QualType returnType,
3203 SmallVectorImpl<QualType> &ArgTypes,
3204 SmallVectorImpl<Expr*> &MsgExprs,
3205 ObjCMethodDecl *Method) {
3206 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003207 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3208 Method ? Method->isVariadic()
3209 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003210 castType = Context->getPointerType(castType);
3211
3212 // build type for containing the objc_msgSend_stret object.
3213 static unsigned stretCount=0;
3214 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003215 std::string str =
3216 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003217 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003218 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003219 str += " {\n\t";
3220 str += name;
3221 str += "(id receiver, SEL sel";
3222 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003223 std::string ArgName = "arg"; ArgName += utostr(i);
3224 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3225 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003226 }
3227 // could be vararg.
3228 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003229 std::string ArgName = "arg"; ArgName += utostr(i);
3230 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3231 Context->getPrintingPolicy());
3232 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003233 }
3234
3235 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003236 str += "\t unsigned size = sizeof(";
3237 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3238
3239 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3240
3241 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3242 str += ")(void *)objc_msgSend)(receiver, sel";
3243 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3244 str += ", arg"; str += utostr(i);
3245 }
3246 // could be vararg.
3247 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3248 str += ", arg"; str += utostr(i);
3249 }
3250 str+= ");\n";
3251
3252 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003253 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3254 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003255
3256
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003257 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3258 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3259 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3260 str += ", arg"; str += utostr(i);
3261 }
3262 // could be vararg.
3263 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3264 str += ", arg"; str += utostr(i);
3265 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003266 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003267
3268
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003269 str += "\t}\n";
3270 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3271 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003272 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003273 SourceLocation FunLocStart;
3274 if (CurFunctionDef)
3275 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3276 else {
3277 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3278 FunLocStart = CurMethodDef->getLocStart();
3279 }
3280
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003281 InsertText(FunLocStart, str);
3282 ++stretCount;
3283
3284 // AST for __Stretn(receiver, args).s;
3285 IdentifierInfo *ID = &Context->Idents.get(name);
3286 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003287 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003288 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003289 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3290 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003291 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003292 castType, VK_LValue, SourceLocation());
3293
3294 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3295 SourceLocation(),
3296 &Context->Idents.get("s"),
3297 returnType, 0,
3298 /*BitWidth=*/0, /*Mutable=*/true,
3299 ICIS_NoInit);
3300 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3301 FieldD->getType(), VK_LValue,
3302 OK_Ordinary);
3303
3304 return ME;
3305}
3306
Fariborz Jahanian11671902012-02-07 17:11:38 +00003307Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3308 SourceLocation StartLoc,
3309 SourceLocation EndLoc) {
3310 if (!SelGetUidFunctionDecl)
3311 SynthSelGetUidFunctionDecl();
3312 if (!MsgSendFunctionDecl)
3313 SynthMsgSendFunctionDecl();
3314 if (!MsgSendSuperFunctionDecl)
3315 SynthMsgSendSuperFunctionDecl();
3316 if (!MsgSendStretFunctionDecl)
3317 SynthMsgSendStretFunctionDecl();
3318 if (!MsgSendSuperStretFunctionDecl)
3319 SynthMsgSendSuperStretFunctionDecl();
3320 if (!MsgSendFpretFunctionDecl)
3321 SynthMsgSendFpretFunctionDecl();
3322 if (!GetClassFunctionDecl)
3323 SynthGetClassFunctionDecl();
3324 if (!GetSuperClassFunctionDecl)
3325 SynthGetSuperClassFunctionDecl();
3326 if (!GetMetaClassFunctionDecl)
3327 SynthGetMetaClassFunctionDecl();
3328
3329 // default to objc_msgSend().
3330 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3331 // May need to use objc_msgSend_stret() as well.
3332 FunctionDecl *MsgSendStretFlavor = 0;
3333 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003334 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003335 if (resultType->isRecordType())
3336 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3337 else if (resultType->isRealFloatingType())
3338 MsgSendFlavor = MsgSendFpretFunctionDecl;
3339 }
3340
3341 // Synthesize a call to objc_msgSend().
3342 SmallVector<Expr*, 8> MsgExprs;
3343 switch (Exp->getReceiverKind()) {
3344 case ObjCMessageExpr::SuperClass: {
3345 MsgSendFlavor = MsgSendSuperFunctionDecl;
3346 if (MsgSendStretFlavor)
3347 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3348 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3349
3350 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3351
3352 SmallVector<Expr*, 4> InitExprs;
3353
3354 // set the receiver to self, the first argument to all methods.
3355 InitExprs.push_back(
3356 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3357 CK_BitCast,
3358 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003359 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003360 Context->getObjCIdType(),
3361 VK_RValue,
3362 SourceLocation()))
3363 ); // set the 'receiver'.
3364
3365 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3366 SmallVector<Expr*, 8> ClsExprs;
3367 QualType argType = Context->getPointerType(Context->CharTy);
3368 ClsExprs.push_back(StringLiteral::Create(*Context,
3369 ClassDecl->getIdentifier()->getName(),
3370 StringLiteral::Ascii, false,
3371 argType, SourceLocation()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003372 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003373 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3374 &ClsExprs[0],
3375 ClsExprs.size(),
3376 StartLoc,
3377 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003378 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003379 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003380 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3381 &ClsExprs[0], ClsExprs.size(),
3382 StartLoc, EndLoc);
3383
3384 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3385 // To turn off a warning, type-cast to 'id'
3386 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3387 NoTypeInfoCStyleCastExpr(Context,
3388 Context->getObjCIdType(),
3389 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003390 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003391 QualType superType = getSuperStructType();
3392 Expr *SuperRep;
3393
3394 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003395 SynthSuperConstructorFunctionDecl();
3396 // Simulate a constructor call...
3397 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003398 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003399 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003400 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003401 superType, VK_LValue,
3402 SourceLocation());
3403 // The code for super is a little tricky to prevent collision with
3404 // the structure definition in the header. The rewriter has it's own
3405 // internal definition (__rw_objc_super) that is uses. This is why
3406 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003407 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003408 //
3409 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3410 Context->getPointerType(SuperRep->getType()),
3411 VK_RValue, OK_Ordinary,
3412 SourceLocation());
3413 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3414 Context->getPointerType(superType),
3415 CK_BitCast, SuperRep);
3416 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003417 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003418 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003419 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003420 SourceLocation());
3421 TypeSourceInfo *superTInfo
3422 = Context->getTrivialTypeSourceInfo(superType);
3423 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3424 superType, VK_LValue,
3425 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003426 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003427 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3428 Context->getPointerType(SuperRep->getType()),
3429 VK_RValue, OK_Ordinary,
3430 SourceLocation());
3431 }
3432 MsgExprs.push_back(SuperRep);
3433 break;
3434 }
3435
3436 case ObjCMessageExpr::Class: {
3437 SmallVector<Expr*, 8> ClsExprs;
3438 QualType argType = Context->getPointerType(Context->CharTy);
3439 ObjCInterfaceDecl *Class
3440 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3441 IdentifierInfo *clsName = Class->getIdentifier();
3442 ClsExprs.push_back(StringLiteral::Create(*Context,
3443 clsName->getName(),
3444 StringLiteral::Ascii, false,
3445 argType, SourceLocation()));
3446 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3447 &ClsExprs[0],
3448 ClsExprs.size(),
3449 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003450 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3451 Context->getObjCIdType(),
3452 CK_BitCast, Cls);
3453 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003454 break;
3455 }
3456
3457 case ObjCMessageExpr::SuperInstance:{
3458 MsgSendFlavor = MsgSendSuperFunctionDecl;
3459 if (MsgSendStretFlavor)
3460 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3461 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3462 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3463 SmallVector<Expr*, 4> InitExprs;
3464
3465 InitExprs.push_back(
3466 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3467 CK_BitCast,
3468 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003469 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003470 Context->getObjCIdType(),
3471 VK_RValue, SourceLocation()))
3472 ); // set the 'receiver'.
3473
3474 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3475 SmallVector<Expr*, 8> ClsExprs;
3476 QualType argType = Context->getPointerType(Context->CharTy);
3477 ClsExprs.push_back(StringLiteral::Create(*Context,
3478 ClassDecl->getIdentifier()->getName(),
3479 StringLiteral::Ascii, false, argType,
3480 SourceLocation()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003481 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003482 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3483 &ClsExprs[0],
3484 ClsExprs.size(),
3485 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003486 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003487 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003488 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3489 &ClsExprs[0], ClsExprs.size(),
3490 StartLoc, EndLoc);
3491
3492 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3493 // To turn off a warning, type-cast to 'id'
3494 InitExprs.push_back(
3495 // set 'super class', using class_getSuperclass().
3496 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3497 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003498 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003499 QualType superType = getSuperStructType();
3500 Expr *SuperRep;
3501
3502 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003503 SynthSuperConstructorFunctionDecl();
3504 // Simulate a constructor call...
3505 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003506 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003507 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003508 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003509 superType, VK_LValue, SourceLocation());
3510 // The code for super is a little tricky to prevent collision with
3511 // the structure definition in the header. The rewriter has it's own
3512 // internal definition (__rw_objc_super) that is uses. This is why
3513 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003514 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003515 //
3516 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3517 Context->getPointerType(SuperRep->getType()),
3518 VK_RValue, OK_Ordinary,
3519 SourceLocation());
3520 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3521 Context->getPointerType(superType),
3522 CK_BitCast, SuperRep);
3523 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003524 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003525 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003526 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003527 SourceLocation());
3528 TypeSourceInfo *superTInfo
3529 = Context->getTrivialTypeSourceInfo(superType);
3530 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3531 superType, VK_RValue, ILE,
3532 false);
3533 }
3534 MsgExprs.push_back(SuperRep);
3535 break;
3536 }
3537
3538 case ObjCMessageExpr::Instance: {
3539 // Remove all type-casts because it may contain objc-style types; e.g.
3540 // Foo<Proto> *.
3541 Expr *recExpr = Exp->getInstanceReceiver();
3542 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3543 recExpr = CE->getSubExpr();
3544 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3545 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3546 ? CK_BlockPointerToObjCPointerCast
3547 : CK_CPointerToObjCPointerCast;
3548
3549 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3550 CK, recExpr);
3551 MsgExprs.push_back(recExpr);
3552 break;
3553 }
3554 }
3555
3556 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3557 SmallVector<Expr*, 8> SelExprs;
3558 QualType argType = Context->getPointerType(Context->CharTy);
3559 SelExprs.push_back(StringLiteral::Create(*Context,
3560 Exp->getSelector().getAsString(),
3561 StringLiteral::Ascii, false,
3562 argType, SourceLocation()));
3563 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3564 &SelExprs[0], SelExprs.size(),
3565 StartLoc,
3566 EndLoc);
3567 MsgExprs.push_back(SelExp);
3568
3569 // Now push any user supplied arguments.
3570 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3571 Expr *userExpr = Exp->getArg(i);
3572 // Make all implicit casts explicit...ICE comes in handy:-)
3573 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3574 // Reuse the ICE type, it is exactly what the doctor ordered.
3575 QualType type = ICE->getType();
3576 if (needToScanForQualifiers(type))
3577 type = Context->getObjCIdType();
3578 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3579 (void)convertBlockPointerToFunctionPointer(type);
3580 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3581 CastKind CK;
3582 if (SubExpr->getType()->isIntegralType(*Context) &&
3583 type->isBooleanType()) {
3584 CK = CK_IntegralToBoolean;
3585 } else if (type->isObjCObjectPointerType()) {
3586 if (SubExpr->getType()->isBlockPointerType()) {
3587 CK = CK_BlockPointerToObjCPointerCast;
3588 } else if (SubExpr->getType()->isPointerType()) {
3589 CK = CK_CPointerToObjCPointerCast;
3590 } else {
3591 CK = CK_BitCast;
3592 }
3593 } else {
3594 CK = CK_BitCast;
3595 }
3596
3597 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3598 }
3599 // Make id<P...> cast into an 'id' cast.
3600 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3601 if (CE->getType()->isObjCQualifiedIdType()) {
3602 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3603 userExpr = CE->getSubExpr();
3604 CastKind CK;
3605 if (userExpr->getType()->isIntegralType(*Context)) {
3606 CK = CK_IntegralToPointer;
3607 } else if (userExpr->getType()->isBlockPointerType()) {
3608 CK = CK_BlockPointerToObjCPointerCast;
3609 } else if (userExpr->getType()->isPointerType()) {
3610 CK = CK_CPointerToObjCPointerCast;
3611 } else {
3612 CK = CK_BitCast;
3613 }
3614 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3615 CK, userExpr);
3616 }
3617 }
3618 MsgExprs.push_back(userExpr);
3619 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3620 // out the argument in the original expression (since we aren't deleting
3621 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3622 //Exp->setArg(i, 0);
3623 }
3624 // Generate the funky cast.
3625 CastExpr *cast;
3626 SmallVector<QualType, 8> ArgTypes;
3627 QualType returnType;
3628
3629 // Push 'id' and 'SEL', the 2 implicit arguments.
3630 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3631 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3632 else
3633 ArgTypes.push_back(Context->getObjCIdType());
3634 ArgTypes.push_back(Context->getObjCSelType());
3635 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3636 // Push any user argument types.
3637 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3638 E = OMD->param_end(); PI != E; ++PI) {
3639 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3640 ? Context->getObjCIdType()
3641 : (*PI)->getType();
3642 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3643 (void)convertBlockPointerToFunctionPointer(t);
3644 ArgTypes.push_back(t);
3645 }
3646 returnType = Exp->getType();
3647 convertToUnqualifiedObjCType(returnType);
3648 (void)convertBlockPointerToFunctionPointer(returnType);
3649 } else {
3650 returnType = Context->getObjCIdType();
3651 }
3652 // Get the type, we will need to reference it in a couple spots.
3653 QualType msgSendType = MsgSendFlavor->getType();
3654
3655 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003656 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003657 VK_LValue, SourceLocation());
3658
3659 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3660 // If we don't do this cast, we get the following bizarre warning/note:
3661 // xx.m:13: warning: function called through a non-compatible type
3662 // xx.m:13: note: if this code is reached, the program will abort
3663 cast = NoTypeInfoCStyleCastExpr(Context,
3664 Context->getPointerType(Context->VoidTy),
3665 CK_BitCast, DRE);
3666
3667 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003668 // If we don't have a method decl, force a variadic cast.
3669 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003670 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003671 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003672 castType = Context->getPointerType(castType);
3673 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3674 cast);
3675
3676 // Don't forget the parens to enforce the proper binding.
3677 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3678
3679 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003680 CallExpr *CE = new (Context)
3681 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003682 Stmt *ReplacingStmt = CE;
3683 if (MsgSendStretFlavor) {
3684 // We have the method which returns a struct/union. Must also generate
3685 // call to objc_msgSend_stret and hang both varieties on a conditional
3686 // expression which dictate which one to envoke depending on size of
3687 // method's return type.
3688
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003689 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3690 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003691 ArgTypes, MsgExprs,
3692 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003693 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003694 }
3695 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3696 return ReplacingStmt;
3697}
3698
3699Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3700 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3701 Exp->getLocEnd());
3702
3703 // Now do the actual rewrite.
3704 ReplaceStmt(Exp, ReplacingStmt);
3705
3706 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3707 return ReplacingStmt;
3708}
3709
3710// typedef struct objc_object Protocol;
3711QualType RewriteModernObjC::getProtocolType() {
3712 if (!ProtocolTypeDecl) {
3713 TypeSourceInfo *TInfo
3714 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3715 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3716 SourceLocation(), SourceLocation(),
3717 &Context->Idents.get("Protocol"),
3718 TInfo);
3719 }
3720 return Context->getTypeDeclType(ProtocolTypeDecl);
3721}
3722
3723/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3724/// a synthesized/forward data reference (to the protocol's metadata).
3725/// The forward references (and metadata) are generated in
3726/// RewriteModernObjC::HandleTranslationUnit().
3727Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003728 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3729 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003730 IdentifierInfo *ID = &Context->Idents.get(Name);
3731 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3732 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003733 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003734 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3735 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003736 CastExpr *castExpr =
3737 NoTypeInfoCStyleCastExpr(
3738 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003739 ReplaceStmt(Exp, castExpr);
3740 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3741 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3742 return castExpr;
3743
3744}
3745
3746bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3747 const char *endBuf) {
3748 while (startBuf < endBuf) {
3749 if (*startBuf == '#') {
3750 // Skip whitespace.
3751 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3752 ;
3753 if (!strncmp(startBuf, "if", strlen("if")) ||
3754 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3755 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3756 !strncmp(startBuf, "define", strlen("define")) ||
3757 !strncmp(startBuf, "undef", strlen("undef")) ||
3758 !strncmp(startBuf, "else", strlen("else")) ||
3759 !strncmp(startBuf, "elif", strlen("elif")) ||
3760 !strncmp(startBuf, "endif", strlen("endif")) ||
3761 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3762 !strncmp(startBuf, "include", strlen("include")) ||
3763 !strncmp(startBuf, "import", strlen("import")) ||
3764 !strncmp(startBuf, "include_next", strlen("include_next")))
3765 return true;
3766 }
3767 startBuf++;
3768 }
3769 return false;
3770}
3771
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003772/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3773/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003774bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003775 TagDecl *Tag,
3776 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003777 if (!IDecl)
3778 return false;
3779 SourceLocation TagLocation;
3780 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3781 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003782 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003783 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003784 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003785 TagLocation = RD->getLocation();
3786 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003787 IDecl->getLocation(), TagLocation);
3788 }
3789 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3790 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3791 return false;
3792 IsNamedDefinition = true;
3793 TagLocation = ED->getLocation();
3794 return Context->getSourceManager().isBeforeInTranslationUnit(
3795 IDecl->getLocation(), TagLocation);
3796
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003797 }
3798 return false;
3799}
3800
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003801/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003802/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003803bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3804 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003805 if (isa<TypedefType>(Type)) {
3806 Result += "\t";
3807 return false;
3808 }
3809
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003810 if (Type->isArrayType()) {
3811 QualType ElemTy = Context->getBaseElementType(Type);
3812 return RewriteObjCFieldDeclType(ElemTy, Result);
3813 }
3814 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003815 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3816 if (RD->isCompleteDefinition()) {
3817 if (RD->isStruct())
3818 Result += "\n\tstruct ";
3819 else if (RD->isUnion())
3820 Result += "\n\tunion ";
3821 else
3822 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003823
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003824 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003825 if (GlobalDefinedTags.count(RD)) {
3826 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003827 Result += " ";
3828 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003829 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003830 Result += " {\n";
3831 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003832 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00003833 FieldDecl *FD = *i;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003834 RewriteObjCFieldDecl(FD, Result);
3835 }
3836 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003837 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003838 }
3839 }
3840 else if (Type->isEnumeralType()) {
3841 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3842 if (ED->isCompleteDefinition()) {
3843 Result += "\n\tenum ";
3844 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003845 if (GlobalDefinedTags.count(ED)) {
3846 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003847 Result += " ";
3848 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003849 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003850
3851 Result += " {\n";
3852 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3853 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3854 Result += "\t"; Result += EC->getName(); Result += " = ";
3855 llvm::APSInt Val = EC->getInitVal();
3856 Result += Val.toString(10);
3857 Result += ",\n";
3858 }
3859 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003860 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003861 }
3862 }
3863
3864 Result += "\t";
3865 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003866 return false;
3867}
3868
3869
3870/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3871/// It handles elaborated types, as well as enum types in the process.
3872void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3873 std::string &Result) {
3874 QualType Type = fieldDecl->getType();
3875 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003876
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003877 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3878 if (!EleboratedType)
3879 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003880 Result += Name;
3881 if (fieldDecl->isBitField()) {
3882 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3883 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003884 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003885 const ArrayType *AT = Context->getAsArrayType(Type);
3886 do {
3887 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003888 Result += "[";
3889 llvm::APInt Dim = CAT->getSize();
3890 Result += utostr(Dim.getZExtValue());
3891 Result += "]";
3892 }
Eli Friedman07bab732012-12-13 01:43:21 +00003893 AT = Context->getAsArrayType(AT->getElementType());
3894 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003895 }
3896
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003897 Result += ";\n";
3898}
3899
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003900/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3901/// named aggregate types into the input buffer.
3902void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3903 std::string &Result) {
3904 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003905 if (isa<TypedefType>(Type))
3906 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003907 if (Type->isArrayType())
3908 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003909 ObjCContainerDecl *IDecl =
3910 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003911
3912 TagDecl *TD = 0;
3913 if (Type->isRecordType()) {
3914 TD = Type->getAs<RecordType>()->getDecl();
3915 }
3916 else if (Type->isEnumeralType()) {
3917 TD = Type->getAs<EnumType>()->getDecl();
3918 }
3919
3920 if (TD) {
3921 if (GlobalDefinedTags.count(TD))
3922 return;
3923
3924 bool IsNamedDefinition = false;
3925 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3926 RewriteObjCFieldDeclType(Type, Result);
3927 Result += ";";
3928 }
3929 if (IsNamedDefinition)
3930 GlobalDefinedTags.insert(TD);
3931 }
3932
3933}
3934
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003935unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3936 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3937 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3938 return IvarGroupNumber[IV];
3939 }
3940 unsigned GroupNo = 0;
3941 SmallVector<const ObjCIvarDecl *, 8> IVars;
3942 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3943 IVD; IVD = IVD->getNextIvar())
3944 IVars.push_back(IVD);
3945
3946 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3947 if (IVars[i]->isBitField()) {
3948 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3949 while (i < e && IVars[i]->isBitField())
3950 IvarGroupNumber[IVars[i++]] = GroupNo;
3951 if (i < e)
3952 --i;
3953 }
3954
3955 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3956 return IvarGroupNumber[IV];
3957}
3958
3959QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3960 ObjCIvarDecl *IV,
3961 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3962 std::string StructTagName;
3963 ObjCIvarBitfieldGroupType(IV, StructTagName);
3964 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3965 Context->getTranslationUnitDecl(),
3966 SourceLocation(), SourceLocation(),
3967 &Context->Idents.get(StructTagName));
3968 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3969 ObjCIvarDecl *Ivar = IVars[i];
3970 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3971 &Context->Idents.get(Ivar->getName()),
3972 Ivar->getType(),
3973 0, /*Expr *BW */Ivar->getBitWidth(), false,
3974 ICIS_NoInit));
3975 }
3976 RD->completeDefinition();
3977 return Context->getTagDeclType(RD);
3978}
3979
3980QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3981 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3982 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3983 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3984 if (GroupRecordType.count(tuple))
3985 return GroupRecordType[tuple];
3986
3987 SmallVector<ObjCIvarDecl *, 8> IVars;
3988 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3989 IVD; IVD = IVD->getNextIvar()) {
3990 if (IVD->isBitField())
3991 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3992 else {
3993 if (!IVars.empty()) {
3994 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3995 // Generate the struct type for this group of bitfield ivars.
3996 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3997 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3998 IVars.clear();
3999 }
4000 }
4001 }
4002 if (!IVars.empty()) {
4003 // Do the last one.
4004 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
4005 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
4006 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
4007 }
4008 QualType RetQT = GroupRecordType[tuple];
4009 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
4010
4011 return RetQT;
4012}
4013
4014/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4015/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4016void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4017 std::string &Result) {
4018 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4019 Result += CDecl->getName();
4020 Result += "__GRBF_";
4021 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4022 Result += utostr(GroupNo);
4023 return;
4024}
4025
4026/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4027/// Name of the struct would be: classname__T_n where n is the group number for
4028/// this ivar.
4029void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4030 std::string &Result) {
4031 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4032 Result += CDecl->getName();
4033 Result += "__T_";
4034 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4035 Result += utostr(GroupNo);
4036 return;
4037}
4038
4039/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4040/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4041/// this ivar.
4042void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4043 std::string &Result) {
4044 Result += "OBJC_IVAR_$_";
4045 ObjCIvarBitfieldGroupDecl(IV, Result);
4046}
4047
4048#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4049 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4050 ++IX; \
4051 if (IX < ENDIX) \
4052 --IX; \
4053}
4054
Fariborz Jahanian11671902012-02-07 17:11:38 +00004055/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4056/// an objective-c class with ivars.
4057void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4058 std::string &Result) {
4059 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4060 assert(CDecl->getName() != "" &&
4061 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004062 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004063 SmallVector<ObjCIvarDecl *, 8> IVars;
4064 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004065 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004066 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004067
Fariborz Jahanian11671902012-02-07 17:11:38 +00004068 SourceLocation LocStart = CDecl->getLocStart();
4069 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004070
Fariborz Jahanian11671902012-02-07 17:11:38 +00004071 const char *startBuf = SM->getCharacterData(LocStart);
4072 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004073
Fariborz Jahanian11671902012-02-07 17:11:38 +00004074 // If no ivars and no root or if its root, directly or indirectly,
4075 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004076 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004077 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4078 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4079 ReplaceText(LocStart, endBuf-startBuf, Result);
4080 return;
4081 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004082
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004083 // Insert named struct/union definitions inside class to
4084 // outer scope. This follows semantics of locally defined
4085 // struct/unions in objective-c classes.
4086 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4087 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004088
4089 // Insert named structs which are syntheized to group ivar bitfields
4090 // to outer scope as well.
4091 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4092 if (IVars[i]->isBitField()) {
4093 ObjCIvarDecl *IV = IVars[i];
4094 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4095 RewriteObjCFieldDeclType(QT, Result);
4096 Result += ";";
4097 // skip over ivar bitfields in this group.
4098 SKIP_BITFIELDS(i , e, IVars);
4099 }
4100
Fariborz Jahanian11671902012-02-07 17:11:38 +00004101 Result += "\nstruct ";
4102 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004103 Result += "_IMPL {\n";
4104
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004105 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004106 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4107 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4108 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004109 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004110
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004111 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4112 if (IVars[i]->isBitField()) {
4113 ObjCIvarDecl *IV = IVars[i];
4114 Result += "\tstruct ";
4115 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4116 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4117 // skip over ivar bitfields in this group.
4118 SKIP_BITFIELDS(i , e, IVars);
4119 }
4120 else
4121 RewriteObjCFieldDecl(IVars[i], Result);
4122 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004123
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004124 Result += "};\n";
4125 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4126 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004127 // Mark this struct as having been generated.
4128 if (!ObjCSynthesizedStructs.insert(CDecl))
4129 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004130}
4131
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004132/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4133/// have been referenced in an ivar access expression.
4134void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4135 std::string &Result) {
4136 // write out ivar offset symbols which have been referenced in an ivar
4137 // access expression.
4138 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4139 if (Ivars.empty())
4140 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004141
4142 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004143 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4144 e = Ivars.end(); i != e; i++) {
4145 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004146 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4147 unsigned GroupNo = 0;
4148 if (IvarDecl->isBitField()) {
4149 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4150 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4151 continue;
4152 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004153 Result += "\n";
4154 if (LangOpts.MicrosoftExt)
4155 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004156 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004157 if (LangOpts.MicrosoftExt &&
4158 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004159 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4160 Result += "__declspec(dllimport) ";
4161
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004162 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004163 if (IvarDecl->isBitField()) {
4164 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4165 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4166 }
4167 else
4168 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004169 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004170 }
4171}
4172
Fariborz Jahanian11671902012-02-07 17:11:38 +00004173//===----------------------------------------------------------------------===//
4174// Meta Data Emission
4175//===----------------------------------------------------------------------===//
4176
4177
4178/// RewriteImplementations - This routine rewrites all method implementations
4179/// and emits meta-data.
4180
4181void RewriteModernObjC::RewriteImplementations() {
4182 int ClsDefCount = ClassImplementation.size();
4183 int CatDefCount = CategoryImplementation.size();
4184
4185 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004186 for (int i = 0; i < ClsDefCount; i++) {
4187 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4188 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4189 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004190 assert(false &&
4191 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004192 RewriteImplementationDecl(OIMP);
4193 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004194
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004195 for (int i = 0; i < CatDefCount; i++) {
4196 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4197 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4198 if (CDecl->isImplicitInterfaceDecl())
4199 assert(false &&
4200 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004201 RewriteImplementationDecl(CIMP);
4202 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004203}
4204
4205void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4206 const std::string &Name,
4207 ValueDecl *VD, bool def) {
4208 assert(BlockByRefDeclNo.count(VD) &&
4209 "RewriteByRefString: ByRef decl missing");
4210 if (def)
4211 ResultStr += "struct ";
4212 ResultStr += "__Block_byref_" + Name +
4213 "_" + utostr(BlockByRefDeclNo[VD]) ;
4214}
4215
4216static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4217 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4218 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4219 return false;
4220}
4221
4222std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4223 StringRef funcName,
4224 std::string Tag) {
4225 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004226 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004227 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004228 SourceLocation BlockLoc = CE->getExprLoc();
4229 std::string S;
4230 ConvertSourceLocationToLineDirective(BlockLoc, S);
4231
4232 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4233 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004234
4235 BlockDecl *BD = CE->getBlockDecl();
4236
4237 if (isa<FunctionNoProtoType>(AFT)) {
4238 // No user-supplied arguments. Still need to pass in a pointer to the
4239 // block (to reference imported block decl refs).
4240 S += "(" + StructRef + " *__cself)";
4241 } else if (BD->param_empty()) {
4242 S += "(" + StructRef + " *__cself)";
4243 } else {
4244 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4245 assert(FT && "SynthesizeBlockFunc: No function proto");
4246 S += '(';
4247 // first add the implicit argument.
4248 S += StructRef + " *__cself, ";
4249 std::string ParamStr;
4250 for (BlockDecl::param_iterator AI = BD->param_begin(),
4251 E = BD->param_end(); AI != E; ++AI) {
4252 if (AI != BD->param_begin()) S += ", ";
4253 ParamStr = (*AI)->getNameAsString();
4254 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004255 (void)convertBlockPointerToFunctionPointer(QT);
4256 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004257 S += ParamStr;
4258 }
4259 if (FT->isVariadic()) {
4260 if (!BD->param_empty()) S += ", ";
4261 S += "...";
4262 }
4263 S += ')';
4264 }
4265 S += " {\n";
4266
4267 // Create local declarations to avoid rewriting all closure decl ref exprs.
4268 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004269 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004270 E = BlockByRefDecls.end(); I != E; ++I) {
4271 S += " ";
4272 std::string Name = (*I)->getNameAsString();
4273 std::string TypeString;
4274 RewriteByRefString(TypeString, Name, (*I));
4275 TypeString += " *";
4276 Name = TypeString + Name;
4277 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4278 }
4279 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004280 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004281 E = BlockByCopyDecls.end(); I != E; ++I) {
4282 S += " ";
4283 // Handle nested closure invocation. For example:
4284 //
4285 // void (^myImportedClosure)(void);
4286 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4287 //
4288 // void (^anotherClosure)(void);
4289 // anotherClosure = ^(void) {
4290 // myImportedClosure(); // import and invoke the closure
4291 // };
4292 //
4293 if (isTopLevelBlockPointerType((*I)->getType())) {
4294 RewriteBlockPointerTypeVariable(S, (*I));
4295 S += " = (";
4296 RewriteBlockPointerType(S, (*I)->getType());
4297 S += ")";
4298 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4299 }
4300 else {
4301 std::string Name = (*I)->getNameAsString();
4302 QualType QT = (*I)->getType();
4303 if (HasLocalVariableExternalStorage(*I))
4304 QT = Context->getPointerType(QT);
4305 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4306 S += Name + " = __cself->" +
4307 (*I)->getNameAsString() + "; // bound by copy\n";
4308 }
4309 }
4310 std::string RewrittenStr = RewrittenBlockExprs[CE];
4311 const char *cstr = RewrittenStr.c_str();
4312 while (*cstr++ != '{') ;
4313 S += cstr;
4314 S += "\n";
4315 return S;
4316}
4317
4318std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4319 StringRef funcName,
4320 std::string Tag) {
4321 std::string StructRef = "struct " + Tag;
4322 std::string S = "static void __";
4323
4324 S += funcName;
4325 S += "_block_copy_" + utostr(i);
4326 S += "(" + StructRef;
4327 S += "*dst, " + StructRef;
4328 S += "*src) {";
4329 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4330 E = ImportedBlockDecls.end(); I != E; ++I) {
4331 ValueDecl *VD = (*I);
4332 S += "_Block_object_assign((void*)&dst->";
4333 S += (*I)->getNameAsString();
4334 S += ", (void*)src->";
4335 S += (*I)->getNameAsString();
4336 if (BlockByRefDeclsPtrSet.count((*I)))
4337 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4338 else if (VD->getType()->isBlockPointerType())
4339 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4340 else
4341 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4342 }
4343 S += "}\n";
4344
4345 S += "\nstatic void __";
4346 S += funcName;
4347 S += "_block_dispose_" + utostr(i);
4348 S += "(" + StructRef;
4349 S += "*src) {";
4350 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4351 E = ImportedBlockDecls.end(); I != E; ++I) {
4352 ValueDecl *VD = (*I);
4353 S += "_Block_object_dispose((void*)src->";
4354 S += (*I)->getNameAsString();
4355 if (BlockByRefDeclsPtrSet.count((*I)))
4356 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4357 else if (VD->getType()->isBlockPointerType())
4358 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4359 else
4360 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4361 }
4362 S += "}\n";
4363 return S;
4364}
4365
4366std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4367 std::string Desc) {
4368 std::string S = "\nstruct " + Tag;
4369 std::string Constructor = " " + Tag;
4370
4371 S += " {\n struct __block_impl impl;\n";
4372 S += " struct " + Desc;
4373 S += "* Desc;\n";
4374
4375 Constructor += "(void *fp, "; // Invoke function pointer.
4376 Constructor += "struct " + Desc; // Descriptor pointer.
4377 Constructor += " *desc";
4378
4379 if (BlockDeclRefs.size()) {
4380 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004381 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004382 E = BlockByCopyDecls.end(); I != E; ++I) {
4383 S += " ";
4384 std::string FieldName = (*I)->getNameAsString();
4385 std::string ArgName = "_" + FieldName;
4386 // Handle nested closure invocation. For example:
4387 //
4388 // void (^myImportedBlock)(void);
4389 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4390 //
4391 // void (^anotherBlock)(void);
4392 // anotherBlock = ^(void) {
4393 // myImportedBlock(); // import and invoke the closure
4394 // };
4395 //
4396 if (isTopLevelBlockPointerType((*I)->getType())) {
4397 S += "struct __block_impl *";
4398 Constructor += ", void *" + ArgName;
4399 } else {
4400 QualType QT = (*I)->getType();
4401 if (HasLocalVariableExternalStorage(*I))
4402 QT = Context->getPointerType(QT);
4403 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4404 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4405 Constructor += ", " + ArgName;
4406 }
4407 S += FieldName + ";\n";
4408 }
4409 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004410 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004411 E = BlockByRefDecls.end(); I != E; ++I) {
4412 S += " ";
4413 std::string FieldName = (*I)->getNameAsString();
4414 std::string ArgName = "_" + FieldName;
4415 {
4416 std::string TypeString;
4417 RewriteByRefString(TypeString, FieldName, (*I));
4418 TypeString += " *";
4419 FieldName = TypeString + FieldName;
4420 ArgName = TypeString + ArgName;
4421 Constructor += ", " + ArgName;
4422 }
4423 S += FieldName + "; // by ref\n";
4424 }
4425 // Finish writing the constructor.
4426 Constructor += ", int flags=0)";
4427 // Initialize all "by copy" arguments.
4428 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004429 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004430 E = BlockByCopyDecls.end(); I != E; ++I) {
4431 std::string Name = (*I)->getNameAsString();
4432 if (firsTime) {
4433 Constructor += " : ";
4434 firsTime = false;
4435 }
4436 else
4437 Constructor += ", ";
4438 if (isTopLevelBlockPointerType((*I)->getType()))
4439 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4440 else
4441 Constructor += Name + "(_" + Name + ")";
4442 }
4443 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004444 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004445 E = BlockByRefDecls.end(); I != E; ++I) {
4446 std::string Name = (*I)->getNameAsString();
4447 if (firsTime) {
4448 Constructor += " : ";
4449 firsTime = false;
4450 }
4451 else
4452 Constructor += ", ";
4453 Constructor += Name + "(_" + Name + "->__forwarding)";
4454 }
4455
4456 Constructor += " {\n";
4457 if (GlobalVarDecl)
4458 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4459 else
4460 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4461 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4462
4463 Constructor += " Desc = desc;\n";
4464 } else {
4465 // Finish writing the constructor.
4466 Constructor += ", int flags=0) {\n";
4467 if (GlobalVarDecl)
4468 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4469 else
4470 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4471 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4472 Constructor += " Desc = desc;\n";
4473 }
4474 Constructor += " ";
4475 Constructor += "}\n";
4476 S += Constructor;
4477 S += "};\n";
4478 return S;
4479}
4480
4481std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4482 std::string ImplTag, int i,
4483 StringRef FunName,
4484 unsigned hasCopy) {
4485 std::string S = "\nstatic struct " + DescTag;
4486
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004487 S += " {\n size_t reserved;\n";
4488 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004489 if (hasCopy) {
4490 S += " void (*copy)(struct ";
4491 S += ImplTag; S += "*, struct ";
4492 S += ImplTag; S += "*);\n";
4493
4494 S += " void (*dispose)(struct ";
4495 S += ImplTag; S += "*);\n";
4496 }
4497 S += "} ";
4498
4499 S += DescTag + "_DATA = { 0, sizeof(struct ";
4500 S += ImplTag + ")";
4501 if (hasCopy) {
4502 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4503 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4504 }
4505 S += "};\n";
4506 return S;
4507}
4508
4509void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4510 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004511 bool RewriteSC = (GlobalVarDecl &&
4512 !Blocks.empty() &&
4513 GlobalVarDecl->getStorageClass() == SC_Static &&
4514 GlobalVarDecl->getType().getCVRQualifiers());
4515 if (RewriteSC) {
4516 std::string SC(" void __");
4517 SC += GlobalVarDecl->getNameAsString();
4518 SC += "() {}";
4519 InsertText(FunLocStart, SC);
4520 }
4521
4522 // Insert closures that were part of the function.
4523 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4524 CollectBlockDeclRefInfo(Blocks[i]);
4525 // Need to copy-in the inner copied-in variables not actually used in this
4526 // block.
4527 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004528 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004529 ValueDecl *VD = Exp->getDecl();
4530 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004531 if (!VD->hasAttr<BlocksAttr>()) {
4532 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4533 BlockByCopyDeclsPtrSet.insert(VD);
4534 BlockByCopyDecls.push_back(VD);
4535 }
4536 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004537 }
John McCall113bee02012-03-10 09:33:50 +00004538
4539 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004540 BlockByRefDeclsPtrSet.insert(VD);
4541 BlockByRefDecls.push_back(VD);
4542 }
John McCall113bee02012-03-10 09:33:50 +00004543
Fariborz Jahanian11671902012-02-07 17:11:38 +00004544 // imported objects in the inner blocks not used in the outer
4545 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004546 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004547 VD->getType()->isBlockPointerType())
4548 ImportedBlockDecls.insert(VD);
4549 }
4550
4551 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4552 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4553
4554 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4555
4556 InsertText(FunLocStart, CI);
4557
4558 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4559
4560 InsertText(FunLocStart, CF);
4561
4562 if (ImportedBlockDecls.size()) {
4563 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4564 InsertText(FunLocStart, HF);
4565 }
4566 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4567 ImportedBlockDecls.size() > 0);
4568 InsertText(FunLocStart, BD);
4569
4570 BlockDeclRefs.clear();
4571 BlockByRefDecls.clear();
4572 BlockByRefDeclsPtrSet.clear();
4573 BlockByCopyDecls.clear();
4574 BlockByCopyDeclsPtrSet.clear();
4575 ImportedBlockDecls.clear();
4576 }
4577 if (RewriteSC) {
4578 // Must insert any 'const/volatile/static here. Since it has been
4579 // removed as result of rewriting of block literals.
4580 std::string SC;
4581 if (GlobalVarDecl->getStorageClass() == SC_Static)
4582 SC = "static ";
4583 if (GlobalVarDecl->getType().isConstQualified())
4584 SC += "const ";
4585 if (GlobalVarDecl->getType().isVolatileQualified())
4586 SC += "volatile ";
4587 if (GlobalVarDecl->getType().isRestrictQualified())
4588 SC += "restrict ";
4589 InsertText(FunLocStart, SC);
4590 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004591 if (GlobalConstructionExp) {
4592 // extra fancy dance for global literal expression.
4593
4594 // Always the latest block expression on the block stack.
4595 std::string Tag = "__";
4596 Tag += FunName;
4597 Tag += "_block_impl_";
4598 Tag += utostr(Blocks.size()-1);
4599 std::string globalBuf = "static ";
4600 globalBuf += Tag; globalBuf += " ";
4601 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004602
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004603 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004604 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004605 PrintingPolicy(LangOpts));
4606 globalBuf += constructorExprBuf.str();
4607 globalBuf += ";\n";
4608 InsertText(FunLocStart, globalBuf);
4609 GlobalConstructionExp = 0;
4610 }
4611
Fariborz Jahanian11671902012-02-07 17:11:38 +00004612 Blocks.clear();
4613 InnerDeclRefsCount.clear();
4614 InnerDeclRefs.clear();
4615 RewrittenBlockExprs.clear();
4616}
4617
4618void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004619 SourceLocation FunLocStart =
4620 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4621 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004622 StringRef FuncName = FD->getName();
4623
4624 SynthesizeBlockLiterals(FunLocStart, FuncName);
4625}
4626
4627static void BuildUniqueMethodName(std::string &Name,
4628 ObjCMethodDecl *MD) {
4629 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4630 Name = IFace->getName();
4631 Name += "__" + MD->getSelector().getAsString();
4632 // Convert colons to underscores.
4633 std::string::size_type loc = 0;
4634 while ((loc = Name.find(":", loc)) != std::string::npos)
4635 Name.replace(loc, 1, "_");
4636}
4637
4638void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4639 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4640 //SourceLocation FunLocStart = MD->getLocStart();
4641 SourceLocation FunLocStart = MD->getLocStart();
4642 std::string FuncName;
4643 BuildUniqueMethodName(FuncName, MD);
4644 SynthesizeBlockLiterals(FunLocStart, FuncName);
4645}
4646
4647void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4648 for (Stmt::child_range CI = S->children(); CI; ++CI)
4649 if (*CI) {
4650 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4651 GetBlockDeclRefExprs(CBE->getBody());
4652 else
4653 GetBlockDeclRefExprs(*CI);
4654 }
4655 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004656 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4657 if (DRE->refersToEnclosingLocal()) {
4658 // FIXME: Handle enums.
4659 if (!isa<FunctionDecl>(DRE->getDecl()))
4660 BlockDeclRefs.push_back(DRE);
4661 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4662 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004663 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004664 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004665
4666 return;
4667}
4668
Craig Topper5603df42013-07-05 19:34:19 +00004669void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4670 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004671 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4672 for (Stmt::child_range CI = S->children(); CI; ++CI)
4673 if (*CI) {
4674 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4675 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4676 GetInnerBlockDeclRefExprs(CBE->getBody(),
4677 InnerBlockDeclRefs,
4678 InnerContexts);
4679 }
4680 else
4681 GetInnerBlockDeclRefExprs(*CI,
4682 InnerBlockDeclRefs,
4683 InnerContexts);
4684
4685 }
4686 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004687 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4688 if (DRE->refersToEnclosingLocal()) {
4689 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4690 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4691 InnerBlockDeclRefs.push_back(DRE);
4692 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4693 if (Var->isFunctionOrMethodVarDecl())
4694 ImportedLocalExternalDecls.insert(Var);
4695 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004696 }
4697
4698 return;
4699}
4700
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004701/// convertObjCTypeToCStyleType - This routine converts such objc types
4702/// as qualified objects, and blocks to their closest c/c++ types that
4703/// it can. It returns true if input type was modified.
4704bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4705 QualType oldT = T;
4706 convertBlockPointerToFunctionPointer(T);
4707 if (T->isFunctionPointerType()) {
4708 QualType PointeeTy;
4709 if (const PointerType* PT = T->getAs<PointerType>()) {
4710 PointeeTy = PT->getPointeeType();
4711 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4712 T = convertFunctionTypeOfBlocks(FT);
4713 T = Context->getPointerType(T);
4714 }
4715 }
4716 }
4717
4718 convertToUnqualifiedObjCType(T);
4719 return T != oldT;
4720}
4721
Fariborz Jahanian11671902012-02-07 17:11:38 +00004722/// convertFunctionTypeOfBlocks - This routine converts a function type
4723/// whose result type may be a block pointer or whose argument type(s)
4724/// might be block pointers to an equivalent function type replacing
4725/// all block pointers to function pointers.
4726QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4727 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4728 // FTP will be null for closures that don't take arguments.
4729 // Generate a funky cast.
4730 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004731 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004732 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004733
4734 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004735 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4736 E = FTP->param_type_end();
4737 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004738 QualType t = *I;
4739 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004740 if (convertObjCTypeToCStyleType(t))
4741 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004742 ArgTypes.push_back(t);
4743 }
4744 }
4745 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004746 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004747 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004748 else FuncType = QualType(FT, 0);
4749 return FuncType;
4750}
4751
4752Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4753 // Navigate to relevant type information.
4754 const BlockPointerType *CPT = 0;
4755
4756 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4757 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004758 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4759 CPT = MExpr->getType()->getAs<BlockPointerType>();
4760 }
4761 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4762 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4763 }
4764 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4765 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4766 else if (const ConditionalOperator *CEXPR =
4767 dyn_cast<ConditionalOperator>(BlockExp)) {
4768 Expr *LHSExp = CEXPR->getLHS();
4769 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4770 Expr *RHSExp = CEXPR->getRHS();
4771 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4772 Expr *CONDExp = CEXPR->getCond();
4773 ConditionalOperator *CondExpr =
4774 new (Context) ConditionalOperator(CONDExp,
4775 SourceLocation(), cast<Expr>(LHSStmt),
4776 SourceLocation(), cast<Expr>(RHSStmt),
4777 Exp->getType(), VK_RValue, OK_Ordinary);
4778 return CondExpr;
4779 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4780 CPT = IRE->getType()->getAs<BlockPointerType>();
4781 } else if (const PseudoObjectExpr *POE
4782 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4783 CPT = POE->getType()->castAs<BlockPointerType>();
4784 } else {
4785 assert(1 && "RewriteBlockClass: Bad type");
4786 }
4787 assert(CPT && "RewriteBlockClass: Bad type");
4788 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4789 assert(FT && "RewriteBlockClass: Bad type");
4790 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4791 // FTP will be null for closures that don't take arguments.
4792
4793 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4794 SourceLocation(), SourceLocation(),
4795 &Context->Idents.get("__block_impl"));
4796 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4797
4798 // Generate a funky cast.
4799 SmallVector<QualType, 8> ArgTypes;
4800
4801 // Push the block argument type.
4802 ArgTypes.push_back(PtrBlock);
4803 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004804 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4805 E = FTP->param_type_end();
4806 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004807 QualType t = *I;
4808 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4809 if (!convertBlockPointerToFunctionPointer(t))
4810 convertToUnqualifiedObjCType(t);
4811 ArgTypes.push_back(t);
4812 }
4813 }
4814 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004815 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004816
4817 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4818
4819 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4820 CK_BitCast,
4821 const_cast<Expr*>(BlockExp));
4822 // Don't forget the parens to enforce the proper binding.
4823 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4824 BlkCast);
4825 //PE->dump();
4826
4827 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4828 SourceLocation(),
4829 &Context->Idents.get("FuncPtr"),
4830 Context->VoidPtrTy, 0,
4831 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004832 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004833 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4834 FD->getType(), VK_LValue,
4835 OK_Ordinary);
4836
4837
4838 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4839 CK_BitCast, ME);
4840 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4841
4842 SmallVector<Expr*, 8> BlkExprs;
4843 // Add the implicit argument.
4844 BlkExprs.push_back(BlkCast);
4845 // Add the user arguments.
4846 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4847 E = Exp->arg_end(); I != E; ++I) {
4848 BlkExprs.push_back(*I);
4849 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004850 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004851 Exp->getType(), VK_RValue,
4852 SourceLocation());
4853 return CE;
4854}
4855
4856// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004857// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004858// For example:
4859//
4860// int main() {
4861// __block Foo *f;
4862// __block int i;
4863//
4864// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004865// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004866// i = 77;
4867// };
4868//}
John McCall113bee02012-03-10 09:33:50 +00004869Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004870 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4871 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004872 ValueDecl *VD = DeclRefExp->getDecl();
4873 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004874
4875 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4876 SourceLocation(),
4877 &Context->Idents.get("__forwarding"),
4878 Context->VoidPtrTy, 0,
4879 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004880 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004881 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4882 FD, SourceLocation(),
4883 FD->getType(), VK_LValue,
4884 OK_Ordinary);
4885
4886 StringRef Name = VD->getName();
4887 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4888 &Context->Idents.get(Name),
4889 Context->VoidPtrTy, 0,
4890 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004891 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004892 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4893 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4894
4895
4896
4897 // Need parens to enforce precedence.
4898 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4899 DeclRefExp->getExprLoc(),
4900 ME);
4901 ReplaceStmt(DeclRefExp, PE);
4902 return PE;
4903}
4904
4905// Rewrites the imported local variable V with external storage
4906// (static, extern, etc.) as *V
4907//
4908Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4909 ValueDecl *VD = DRE->getDecl();
4910 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4911 if (!ImportedLocalExternalDecls.count(Var))
4912 return DRE;
4913 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4914 VK_LValue, OK_Ordinary,
4915 DRE->getLocation());
4916 // Need parens to enforce precedence.
4917 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4918 Exp);
4919 ReplaceStmt(DRE, PE);
4920 return PE;
4921}
4922
4923void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4924 SourceLocation LocStart = CE->getLParenLoc();
4925 SourceLocation LocEnd = CE->getRParenLoc();
4926
4927 // Need to avoid trying to rewrite synthesized casts.
4928 if (LocStart.isInvalid())
4929 return;
4930 // Need to avoid trying to rewrite casts contained in macros.
4931 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4932 return;
4933
4934 const char *startBuf = SM->getCharacterData(LocStart);
4935 const char *endBuf = SM->getCharacterData(LocEnd);
4936 QualType QT = CE->getType();
4937 const Type* TypePtr = QT->getAs<Type>();
4938 if (isa<TypeOfExprType>(TypePtr)) {
4939 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4940 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4941 std::string TypeAsString = "(";
4942 RewriteBlockPointerType(TypeAsString, QT);
4943 TypeAsString += ")";
4944 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4945 return;
4946 }
4947 // advance the location to startArgList.
4948 const char *argPtr = startBuf;
4949
4950 while (*argPtr++ && (argPtr < endBuf)) {
4951 switch (*argPtr) {
4952 case '^':
4953 // Replace the '^' with '*'.
4954 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4955 ReplaceText(LocStart, 1, "*");
4956 break;
4957 }
4958 }
4959 return;
4960}
4961
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004962void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4963 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004964 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4965 CastKind != CK_AnyPointerToBlockPointerCast)
4966 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004967
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004968 QualType QT = IC->getType();
4969 (void)convertBlockPointerToFunctionPointer(QT);
4970 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4971 std::string Str = "(";
4972 Str += TypeString;
4973 Str += ")";
4974 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4975
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004976 return;
4977}
4978
Fariborz Jahanian11671902012-02-07 17:11:38 +00004979void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4980 SourceLocation DeclLoc = FD->getLocation();
4981 unsigned parenCount = 0;
4982
4983 // We have 1 or more arguments that have closure pointers.
4984 const char *startBuf = SM->getCharacterData(DeclLoc);
4985 const char *startArgList = strchr(startBuf, '(');
4986
4987 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4988
4989 parenCount++;
4990 // advance the location to startArgList.
4991 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4992 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4993
4994 const char *argPtr = startArgList;
4995
4996 while (*argPtr++ && parenCount) {
4997 switch (*argPtr) {
4998 case '^':
4999 // Replace the '^' with '*'.
5000 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
5001 ReplaceText(DeclLoc, 1, "*");
5002 break;
5003 case '(':
5004 parenCount++;
5005 break;
5006 case ')':
5007 parenCount--;
5008 break;
5009 }
5010 }
5011 return;
5012}
5013
5014bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
5015 const FunctionProtoType *FTP;
5016 const PointerType *PT = QT->getAs<PointerType>();
5017 if (PT) {
5018 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5019 } else {
5020 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5021 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5022 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5023 }
5024 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005025 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
5026 E = FTP->param_type_end();
5027 I != E; ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +00005028 if (isTopLevelBlockPointerType(*I))
5029 return true;
5030 }
5031 return false;
5032}
5033
5034bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5035 const FunctionProtoType *FTP;
5036 const PointerType *PT = QT->getAs<PointerType>();
5037 if (PT) {
5038 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5039 } else {
5040 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5041 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5042 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5043 }
5044 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005045 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
5046 E = FTP->param_type_end();
5047 I != E; ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005048 if ((*I)->isObjCQualifiedIdType())
5049 return true;
5050 if ((*I)->isObjCObjectPointerType() &&
5051 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5052 return true;
5053 }
5054
5055 }
5056 return false;
5057}
5058
5059void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5060 const char *&RParen) {
5061 const char *argPtr = strchr(Name, '(');
5062 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5063
5064 LParen = argPtr; // output the start.
5065 argPtr++; // skip past the left paren.
5066 unsigned parenCount = 1;
5067
5068 while (*argPtr && parenCount) {
5069 switch (*argPtr) {
5070 case '(': parenCount++; break;
5071 case ')': parenCount--; break;
5072 default: break;
5073 }
5074 if (parenCount) argPtr++;
5075 }
5076 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5077 RParen = argPtr; // output the end
5078}
5079
5080void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5081 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5082 RewriteBlockPointerFunctionArgs(FD);
5083 return;
5084 }
5085 // Handle Variables and Typedefs.
5086 SourceLocation DeclLoc = ND->getLocation();
5087 QualType DeclT;
5088 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5089 DeclT = VD->getType();
5090 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5091 DeclT = TDD->getUnderlyingType();
5092 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5093 DeclT = FD->getType();
5094 else
5095 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5096
5097 const char *startBuf = SM->getCharacterData(DeclLoc);
5098 const char *endBuf = startBuf;
5099 // scan backward (from the decl location) for the end of the previous decl.
5100 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5101 startBuf--;
5102 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5103 std::string buf;
5104 unsigned OrigLength=0;
5105 // *startBuf != '^' if we are dealing with a pointer to function that
5106 // may take block argument types (which will be handled below).
5107 if (*startBuf == '^') {
5108 // Replace the '^' with '*', computing a negative offset.
5109 buf = '*';
5110 startBuf++;
5111 OrigLength++;
5112 }
5113 while (*startBuf != ')') {
5114 buf += *startBuf;
5115 startBuf++;
5116 OrigLength++;
5117 }
5118 buf += ')';
5119 OrigLength++;
5120
5121 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5122 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5123 // Replace the '^' with '*' for arguments.
5124 // Replace id<P> with id/*<>*/
5125 DeclLoc = ND->getLocation();
5126 startBuf = SM->getCharacterData(DeclLoc);
5127 const char *argListBegin, *argListEnd;
5128 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5129 while (argListBegin < argListEnd) {
5130 if (*argListBegin == '^')
5131 buf += '*';
5132 else if (*argListBegin == '<') {
5133 buf += "/*";
5134 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005135 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005136 while (*argListBegin != '>') {
5137 buf += *argListBegin++;
5138 OrigLength++;
5139 }
5140 buf += *argListBegin;
5141 buf += "*/";
5142 }
5143 else
5144 buf += *argListBegin;
5145 argListBegin++;
5146 OrigLength++;
5147 }
5148 buf += ')';
5149 OrigLength++;
5150 }
5151 ReplaceText(Start, OrigLength, buf);
5152
5153 return;
5154}
5155
5156
5157/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5158/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5159/// struct Block_byref_id_object *src) {
5160/// _Block_object_assign (&_dest->object, _src->object,
5161/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5162/// [|BLOCK_FIELD_IS_WEAK]) // object
5163/// _Block_object_assign(&_dest->object, _src->object,
5164/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5165/// [|BLOCK_FIELD_IS_WEAK]) // block
5166/// }
5167/// And:
5168/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5169/// _Block_object_dispose(_src->object,
5170/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5171/// [|BLOCK_FIELD_IS_WEAK]) // object
5172/// _Block_object_dispose(_src->object,
5173/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5174/// [|BLOCK_FIELD_IS_WEAK]) // block
5175/// }
5176
5177std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5178 int flag) {
5179 std::string S;
5180 if (CopyDestroyCache.count(flag))
5181 return S;
5182 CopyDestroyCache.insert(flag);
5183 S = "static void __Block_byref_id_object_copy_";
5184 S += utostr(flag);
5185 S += "(void *dst, void *src) {\n";
5186
5187 // offset into the object pointer is computed as:
5188 // void * + void* + int + int + void* + void *
5189 unsigned IntSize =
5190 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5191 unsigned VoidPtrSize =
5192 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5193
5194 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5195 S += " _Block_object_assign((char*)dst + ";
5196 S += utostr(offset);
5197 S += ", *(void * *) ((char*)src + ";
5198 S += utostr(offset);
5199 S += "), ";
5200 S += utostr(flag);
5201 S += ");\n}\n";
5202
5203 S += "static void __Block_byref_id_object_dispose_";
5204 S += utostr(flag);
5205 S += "(void *src) {\n";
5206 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5207 S += utostr(offset);
5208 S += "), ";
5209 S += utostr(flag);
5210 S += ");\n}\n";
5211 return S;
5212}
5213
5214/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5215/// the declaration into:
5216/// struct __Block_byref_ND {
5217/// void *__isa; // NULL for everything except __weak pointers
5218/// struct __Block_byref_ND *__forwarding;
5219/// int32_t __flags;
5220/// int32_t __size;
5221/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5222/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5223/// typex ND;
5224/// };
5225///
5226/// It then replaces declaration of ND variable with:
5227/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5228/// __size=sizeof(struct __Block_byref_ND),
5229/// ND=initializer-if-any};
5230///
5231///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005232void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5233 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005234 int flag = 0;
5235 int isa = 0;
5236 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5237 if (DeclLoc.isInvalid())
5238 // If type location is missing, it is because of missing type (a warning).
5239 // Use variable's location which is good for this case.
5240 DeclLoc = ND->getLocation();
5241 const char *startBuf = SM->getCharacterData(DeclLoc);
5242 SourceLocation X = ND->getLocEnd();
5243 X = SM->getExpansionLoc(X);
5244 const char *endBuf = SM->getCharacterData(X);
5245 std::string Name(ND->getNameAsString());
5246 std::string ByrefType;
5247 RewriteByRefString(ByrefType, Name, ND, true);
5248 ByrefType += " {\n";
5249 ByrefType += " void *__isa;\n";
5250 RewriteByRefString(ByrefType, Name, ND);
5251 ByrefType += " *__forwarding;\n";
5252 ByrefType += " int __flags;\n";
5253 ByrefType += " int __size;\n";
5254 // Add void *__Block_byref_id_object_copy;
5255 // void *__Block_byref_id_object_dispose; if needed.
5256 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005257 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005258 if (HasCopyAndDispose) {
5259 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5260 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5261 }
5262
5263 QualType T = Ty;
5264 (void)convertBlockPointerToFunctionPointer(T);
5265 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5266
5267 ByrefType += " " + Name + ";\n";
5268 ByrefType += "};\n";
5269 // Insert this type in global scope. It is needed by helper function.
5270 SourceLocation FunLocStart;
5271 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005272 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005273 else {
5274 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5275 FunLocStart = CurMethodDef->getLocStart();
5276 }
5277 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005278
Fariborz Jahanian11671902012-02-07 17:11:38 +00005279 if (Ty.isObjCGCWeak()) {
5280 flag |= BLOCK_FIELD_IS_WEAK;
5281 isa = 1;
5282 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005283 if (HasCopyAndDispose) {
5284 flag = BLOCK_BYREF_CALLER;
5285 QualType Ty = ND->getType();
5286 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5287 if (Ty->isBlockPointerType())
5288 flag |= BLOCK_FIELD_IS_BLOCK;
5289 else
5290 flag |= BLOCK_FIELD_IS_OBJECT;
5291 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5292 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005293 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005294 }
5295
5296 // struct __Block_byref_ND ND =
5297 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5298 // initializer-if-any};
5299 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005300 // FIXME. rewriter does not support __block c++ objects which
5301 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005302 if (hasInit)
5303 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5304 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5305 if (CXXDecl && CXXDecl->isDefaultConstructor())
5306 hasInit = false;
5307 }
5308
Fariborz Jahanian11671902012-02-07 17:11:38 +00005309 unsigned flags = 0;
5310 if (HasCopyAndDispose)
5311 flags |= BLOCK_HAS_COPY_DISPOSE;
5312 Name = ND->getNameAsString();
5313 ByrefType.clear();
5314 RewriteByRefString(ByrefType, Name, ND);
5315 std::string ForwardingCastType("(");
5316 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005317 ByrefType += " " + Name + " = {(void*)";
5318 ByrefType += utostr(isa);
5319 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5320 ByrefType += utostr(flags);
5321 ByrefType += ", ";
5322 ByrefType += "sizeof(";
5323 RewriteByRefString(ByrefType, Name, ND);
5324 ByrefType += ")";
5325 if (HasCopyAndDispose) {
5326 ByrefType += ", __Block_byref_id_object_copy_";
5327 ByrefType += utostr(flag);
5328 ByrefType += ", __Block_byref_id_object_dispose_";
5329 ByrefType += utostr(flag);
5330 }
5331
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005332 if (!firstDecl) {
5333 // In multiple __block declarations, and for all but 1st declaration,
5334 // find location of the separating comma. This would be start location
5335 // where new text is to be inserted.
5336 DeclLoc = ND->getLocation();
5337 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5338 const char *commaBuf = startDeclBuf;
5339 while (*commaBuf != ',')
5340 commaBuf--;
5341 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5342 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5343 startBuf = commaBuf;
5344 }
5345
Fariborz Jahanian11671902012-02-07 17:11:38 +00005346 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005347 ByrefType += "};\n";
5348 unsigned nameSize = Name.size();
5349 // for block or function pointer declaration. Name is aleady
5350 // part of the declaration.
5351 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5352 nameSize = 1;
5353 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5354 }
5355 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005356 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005357 SourceLocation startLoc;
5358 Expr *E = ND->getInit();
5359 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5360 startLoc = ECE->getLParenLoc();
5361 else
5362 startLoc = E->getLocStart();
5363 startLoc = SM->getExpansionLoc(startLoc);
5364 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005365 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005366
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005367 const char separator = lastDecl ? ';' : ',';
5368 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5369 const char *separatorBuf = strchr(startInitializerBuf, separator);
5370 assert((*separatorBuf == separator) &&
5371 "RewriteByRefVar: can't find ';' or ','");
5372 SourceLocation separatorLoc =
5373 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5374
5375 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005376 }
5377 return;
5378}
5379
5380void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5381 // Add initializers for any closure decl refs.
5382 GetBlockDeclRefExprs(Exp->getBody());
5383 if (BlockDeclRefs.size()) {
5384 // Unique all "by copy" declarations.
5385 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005386 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005387 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5388 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5389 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5390 }
5391 }
5392 // Unique all "by ref" declarations.
5393 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005394 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005395 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5396 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5397 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5398 }
5399 }
5400 // Find any imported blocks...they will need special attention.
5401 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005402 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005403 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5404 BlockDeclRefs[i]->getType()->isBlockPointerType())
5405 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5406 }
5407}
5408
5409FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5410 IdentifierInfo *ID = &Context->Idents.get(name);
5411 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5412 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5413 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005414 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005415}
5416
5417Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005418 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005419
Fariborz Jahanian11671902012-02-07 17:11:38 +00005420 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005421
Fariborz Jahanian11671902012-02-07 17:11:38 +00005422 Blocks.push_back(Exp);
5423
5424 CollectBlockDeclRefInfo(Exp);
5425
5426 // Add inner imported variables now used in current block.
5427 int countOfInnerDecls = 0;
5428 if (!InnerBlockDeclRefs.empty()) {
5429 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005430 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005431 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005432 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005433 // We need to save the copied-in variables in nested
5434 // blocks because it is needed at the end for some of the API generations.
5435 // See SynthesizeBlockLiterals routine.
5436 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5437 BlockDeclRefs.push_back(Exp);
5438 BlockByCopyDeclsPtrSet.insert(VD);
5439 BlockByCopyDecls.push_back(VD);
5440 }
John McCall113bee02012-03-10 09:33:50 +00005441 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005442 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5443 BlockDeclRefs.push_back(Exp);
5444 BlockByRefDeclsPtrSet.insert(VD);
5445 BlockByRefDecls.push_back(VD);
5446 }
5447 }
5448 // Find any imported blocks...they will need special attention.
5449 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005450 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005451 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5452 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5453 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5454 }
5455 InnerDeclRefsCount.push_back(countOfInnerDecls);
5456
5457 std::string FuncName;
5458
5459 if (CurFunctionDef)
5460 FuncName = CurFunctionDef->getNameAsString();
5461 else if (CurMethodDef)
5462 BuildUniqueMethodName(FuncName, CurMethodDef);
5463 else if (GlobalVarDecl)
5464 FuncName = std::string(GlobalVarDecl->getNameAsString());
5465
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005466 bool GlobalBlockExpr =
5467 block->getDeclContext()->getRedeclContext()->isFileContext();
5468
5469 if (GlobalBlockExpr && !GlobalVarDecl) {
5470 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5471 GlobalBlockExpr = false;
5472 }
5473
Fariborz Jahanian11671902012-02-07 17:11:38 +00005474 std::string BlockNumber = utostr(Blocks.size()-1);
5475
Fariborz Jahanian11671902012-02-07 17:11:38 +00005476 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5477
5478 // Get a pointer to the function type so we can cast appropriately.
5479 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5480 QualType FType = Context->getPointerType(BFT);
5481
5482 FunctionDecl *FD;
5483 Expr *NewRep;
5484
Benjamin Kramer60509af2013-09-09 14:48:42 +00005485 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005486 std::string Tag;
5487
5488 if (GlobalBlockExpr)
5489 Tag = "__global_";
5490 else
5491 Tag = "__";
5492 Tag += FuncName + "_block_impl_" + BlockNumber;
5493
Fariborz Jahanian11671902012-02-07 17:11:38 +00005494 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005495 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005496 SourceLocation());
5497
5498 SmallVector<Expr*, 4> InitExprs;
5499
5500 // Initialize the block function.
5501 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005502 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5503 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005504 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5505 CK_BitCast, Arg);
5506 InitExprs.push_back(castExpr);
5507
5508 // Initialize the block descriptor.
5509 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5510
5511 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5512 SourceLocation(), SourceLocation(),
5513 &Context->Idents.get(DescData.c_str()),
5514 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005515 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005516 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005517 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005518 Context->VoidPtrTy,
5519 VK_LValue,
5520 SourceLocation()),
5521 UO_AddrOf,
5522 Context->getPointerType(Context->VoidPtrTy),
5523 VK_RValue, OK_Ordinary,
5524 SourceLocation());
5525 InitExprs.push_back(DescRefExpr);
5526
5527 // Add initializers for any closure decl refs.
5528 if (BlockDeclRefs.size()) {
5529 Expr *Exp;
5530 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005531 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005532 E = BlockByCopyDecls.end(); I != E; ++I) {
5533 if (isObjCType((*I)->getType())) {
5534 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5535 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005536 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5537 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005538 if (HasLocalVariableExternalStorage(*I)) {
5539 QualType QT = (*I)->getType();
5540 QT = Context->getPointerType(QT);
5541 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5542 OK_Ordinary, SourceLocation());
5543 }
5544 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5545 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005546 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5547 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005548 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5549 CK_BitCast, Arg);
5550 } else {
5551 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005552 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5553 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005554 if (HasLocalVariableExternalStorage(*I)) {
5555 QualType QT = (*I)->getType();
5556 QT = Context->getPointerType(QT);
5557 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5558 OK_Ordinary, SourceLocation());
5559 }
5560
5561 }
5562 InitExprs.push_back(Exp);
5563 }
5564 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005565 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005566 E = BlockByRefDecls.end(); I != E; ++I) {
5567 ValueDecl *ND = (*I);
5568 std::string Name(ND->getNameAsString());
5569 std::string RecName;
5570 RewriteByRefString(RecName, Name, ND, true);
5571 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5572 + sizeof("struct"));
5573 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5574 SourceLocation(), SourceLocation(),
5575 II);
5576 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5577 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5578
5579 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005580 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005581 SourceLocation());
5582 bool isNestedCapturedVar = false;
5583 if (block)
5584 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5585 ce = block->capture_end(); ci != ce; ++ci) {
5586 const VarDecl *variable = ci->getVariable();
5587 if (variable == ND && ci->isNested()) {
5588 assert (ci->isByRef() &&
5589 "SynthBlockInitExpr - captured block variable is not byref");
5590 isNestedCapturedVar = true;
5591 break;
5592 }
5593 }
5594 // captured nested byref variable has its address passed. Do not take
5595 // its address again.
5596 if (!isNestedCapturedVar)
5597 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5598 Context->getPointerType(Exp->getType()),
5599 VK_RValue, OK_Ordinary, SourceLocation());
5600 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5601 InitExprs.push_back(Exp);
5602 }
5603 }
5604 if (ImportedBlockDecls.size()) {
5605 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5606 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5607 unsigned IntSize =
5608 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5609 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5610 Context->IntTy, SourceLocation());
5611 InitExprs.push_back(FlagExp);
5612 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005613 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005614 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005615
5616 if (GlobalBlockExpr) {
5617 assert (GlobalConstructionExp == 0 &&
5618 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5619 GlobalConstructionExp = NewRep;
5620 NewRep = DRE;
5621 }
5622
Fariborz Jahanian11671902012-02-07 17:11:38 +00005623 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5624 Context->getPointerType(NewRep->getType()),
5625 VK_RValue, OK_Ordinary, SourceLocation());
5626 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5627 NewRep);
5628 BlockDeclRefs.clear();
5629 BlockByRefDecls.clear();
5630 BlockByRefDeclsPtrSet.clear();
5631 BlockByCopyDecls.clear();
5632 BlockByCopyDeclsPtrSet.clear();
5633 ImportedBlockDecls.clear();
5634 return NewRep;
5635}
5636
5637bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5638 if (const ObjCForCollectionStmt * CS =
5639 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5640 return CS->getElement() == DS;
5641 return false;
5642}
5643
5644//===----------------------------------------------------------------------===//
5645// Function Body / Expression rewriting
5646//===----------------------------------------------------------------------===//
5647
5648Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5649 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5650 isa<DoStmt>(S) || isa<ForStmt>(S))
5651 Stmts.push_back(S);
5652 else if (isa<ObjCForCollectionStmt>(S)) {
5653 Stmts.push_back(S);
5654 ObjCBcLabelNo.push_back(++BcLabelCount);
5655 }
5656
5657 // Pseudo-object operations and ivar references need special
5658 // treatment because we're going to recursively rewrite them.
5659 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5660 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5661 return RewritePropertyOrImplicitSetter(PseudoOp);
5662 } else {
5663 return RewritePropertyOrImplicitGetter(PseudoOp);
5664 }
5665 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5666 return RewriteObjCIvarRefExpr(IvarRefExpr);
5667 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005668 else if (isa<OpaqueValueExpr>(S))
5669 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005670
5671 SourceRange OrigStmtRange = S->getSourceRange();
5672
5673 // Perform a bottom up rewrite of all children.
5674 for (Stmt::child_range CI = S->children(); CI; ++CI)
5675 if (*CI) {
5676 Stmt *childStmt = (*CI);
5677 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5678 if (newStmt) {
5679 *CI = newStmt;
5680 }
5681 }
5682
5683 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005684 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005685 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5686 InnerContexts.insert(BE->getBlockDecl());
5687 ImportedLocalExternalDecls.clear();
5688 GetInnerBlockDeclRefExprs(BE->getBody(),
5689 InnerBlockDeclRefs, InnerContexts);
5690 // Rewrite the block body in place.
5691 Stmt *SaveCurrentBody = CurrentBody;
5692 CurrentBody = BE->getBody();
5693 PropParentMap = 0;
5694 // block literal on rhs of a property-dot-sytax assignment
5695 // must be replaced by its synthesize ast so getRewrittenText
5696 // works as expected. In this case, what actually ends up on RHS
5697 // is the blockTranscribed which is the helper function for the
5698 // block literal; as in: self.c = ^() {[ace ARR];};
5699 bool saveDisableReplaceStmt = DisableReplaceStmt;
5700 DisableReplaceStmt = false;
5701 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5702 DisableReplaceStmt = saveDisableReplaceStmt;
5703 CurrentBody = SaveCurrentBody;
5704 PropParentMap = 0;
5705 ImportedLocalExternalDecls.clear();
5706 // Now we snarf the rewritten text and stash it away for later use.
5707 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5708 RewrittenBlockExprs[BE] = Str;
5709
5710 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5711
5712 //blockTranscribed->dump();
5713 ReplaceStmt(S, blockTranscribed);
5714 return blockTranscribed;
5715 }
5716 // Handle specific things.
5717 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5718 return RewriteAtEncode(AtEncode);
5719
5720 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5721 return RewriteAtSelector(AtSelector);
5722
5723 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5724 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005725
5726 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5727 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005728
Patrick Beard0caa3942012-04-19 00:25:12 +00005729 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5730 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005731
5732 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5733 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005734
5735 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5736 dyn_cast<ObjCDictionaryLiteral>(S))
5737 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005738
5739 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5740#if 0
5741 // Before we rewrite it, put the original message expression in a comment.
5742 SourceLocation startLoc = MessExpr->getLocStart();
5743 SourceLocation endLoc = MessExpr->getLocEnd();
5744
5745 const char *startBuf = SM->getCharacterData(startLoc);
5746 const char *endBuf = SM->getCharacterData(endLoc);
5747
5748 std::string messString;
5749 messString += "// ";
5750 messString.append(startBuf, endBuf-startBuf+1);
5751 messString += "\n";
5752
5753 // FIXME: Missing definition of
5754 // InsertText(clang::SourceLocation, char const*, unsigned int).
5755 // InsertText(startLoc, messString.c_str(), messString.size());
5756 // Tried this, but it didn't work either...
5757 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5758#endif
5759 return RewriteMessageExpr(MessExpr);
5760 }
5761
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005762 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5763 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5764 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5765 }
5766
Fariborz Jahanian11671902012-02-07 17:11:38 +00005767 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5768 return RewriteObjCTryStmt(StmtTry);
5769
5770 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5771 return RewriteObjCSynchronizedStmt(StmtTry);
5772
5773 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5774 return RewriteObjCThrowStmt(StmtThrow);
5775
5776 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5777 return RewriteObjCProtocolExpr(ProtocolExp);
5778
5779 if (ObjCForCollectionStmt *StmtForCollection =
5780 dyn_cast<ObjCForCollectionStmt>(S))
5781 return RewriteObjCForCollectionStmt(StmtForCollection,
5782 OrigStmtRange.getEnd());
5783 if (BreakStmt *StmtBreakStmt =
5784 dyn_cast<BreakStmt>(S))
5785 return RewriteBreakStmt(StmtBreakStmt);
5786 if (ContinueStmt *StmtContinueStmt =
5787 dyn_cast<ContinueStmt>(S))
5788 return RewriteContinueStmt(StmtContinueStmt);
5789
5790 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5791 // and cast exprs.
5792 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5793 // FIXME: What we're doing here is modifying the type-specifier that
5794 // precedes the first Decl. In the future the DeclGroup should have
5795 // a separate type-specifier that we can rewrite.
5796 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5797 // the context of an ObjCForCollectionStmt. For example:
5798 // NSArray *someArray;
5799 // for (id <FooProtocol> index in someArray) ;
5800 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5801 // and it depends on the original text locations/positions.
5802 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5803 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5804
5805 // Blocks rewrite rules.
5806 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5807 DI != DE; ++DI) {
5808 Decl *SD = *DI;
5809 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5810 if (isTopLevelBlockPointerType(ND->getType()))
5811 RewriteBlockPointerDecl(ND);
5812 else if (ND->getType()->isFunctionPointerType())
5813 CheckFunctionPointerDecl(ND->getType(), ND);
5814 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5815 if (VD->hasAttr<BlocksAttr>()) {
5816 static unsigned uniqueByrefDeclCount = 0;
5817 assert(!BlockByRefDeclNo.count(ND) &&
5818 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5819 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005820 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005821 }
5822 else
5823 RewriteTypeOfDecl(VD);
5824 }
5825 }
5826 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5827 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5828 RewriteBlockPointerDecl(TD);
5829 else if (TD->getUnderlyingType()->isFunctionPointerType())
5830 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5831 }
5832 }
5833 }
5834
5835 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5836 RewriteObjCQualifiedInterfaceTypes(CE);
5837
5838 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5839 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5840 assert(!Stmts.empty() && "Statement stack is empty");
5841 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5842 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5843 && "Statement stack mismatch");
5844 Stmts.pop_back();
5845 }
5846 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005847 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5848 ValueDecl *VD = DRE->getDecl();
5849 if (VD->hasAttr<BlocksAttr>())
5850 return RewriteBlockDeclRefExpr(DRE);
5851 if (HasLocalVariableExternalStorage(VD))
5852 return RewriteLocalVariableExternalStorage(DRE);
5853 }
5854
5855 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5856 if (CE->getCallee()->getType()->isBlockPointerType()) {
5857 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5858 ReplaceStmt(S, BlockCall);
5859 return BlockCall;
5860 }
5861 }
5862 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5863 RewriteCastExpr(CE);
5864 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005865 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5866 RewriteImplicitCastObjCExpr(ICE);
5867 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005868#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005869
Fariborz Jahanian11671902012-02-07 17:11:38 +00005870 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5871 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5872 ICE->getSubExpr(),
5873 SourceLocation());
5874 // Get the new text.
5875 std::string SStr;
5876 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005877 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005878 const std::string &Str = Buf.str();
5879
5880 printf("CAST = %s\n", &Str[0]);
5881 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5882 delete S;
5883 return Replacement;
5884 }
5885#endif
5886 // Return this stmt unmodified.
5887 return S;
5888}
5889
5890void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5891 for (RecordDecl::field_iterator i = RD->field_begin(),
5892 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00005893 FieldDecl *FD = *i;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005894 if (isTopLevelBlockPointerType(FD->getType()))
5895 RewriteBlockPointerDecl(FD);
5896 if (FD->getType()->isObjCQualifiedIdType() ||
5897 FD->getType()->isObjCQualifiedInterfaceType())
5898 RewriteObjCQualifiedInterfaceTypes(FD);
5899 }
5900}
5901
5902/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5903/// main file of the input.
5904void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5905 switch (D->getKind()) {
5906 case Decl::Function: {
5907 FunctionDecl *FD = cast<FunctionDecl>(D);
5908 if (FD->isOverloadedOperator())
5909 return;
5910
5911 // Since function prototypes don't have ParmDecl's, we check the function
5912 // prototype. This enables us to rewrite function declarations and
5913 // definitions using the same code.
5914 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5915
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005916 if (!FD->isThisDeclarationADefinition())
5917 break;
5918
Fariborz Jahanian11671902012-02-07 17:11:38 +00005919 // FIXME: If this should support Obj-C++, support CXXTryStmt
5920 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5921 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005922 CurrentBody = Body;
5923 Body =
5924 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5925 FD->setBody(Body);
5926 CurrentBody = 0;
5927 if (PropParentMap) {
5928 delete PropParentMap;
5929 PropParentMap = 0;
5930 }
5931 // This synthesizes and inserts the block "impl" struct, invoke function,
5932 // and any copy/dispose helper functions.
5933 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005934 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005935 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005936 }
5937 break;
5938 }
5939 case Decl::ObjCMethod: {
5940 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5941 if (CompoundStmt *Body = MD->getCompoundBody()) {
5942 CurMethodDef = MD;
5943 CurrentBody = Body;
5944 Body =
5945 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5946 MD->setBody(Body);
5947 CurrentBody = 0;
5948 if (PropParentMap) {
5949 delete PropParentMap;
5950 PropParentMap = 0;
5951 }
5952 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005953 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005954 CurMethodDef = 0;
5955 }
5956 break;
5957 }
5958 case Decl::ObjCImplementation: {
5959 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5960 ClassImplementation.push_back(CI);
5961 break;
5962 }
5963 case Decl::ObjCCategoryImpl: {
5964 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5965 CategoryImplementation.push_back(CI);
5966 break;
5967 }
5968 case Decl::Var: {
5969 VarDecl *VD = cast<VarDecl>(D);
5970 RewriteObjCQualifiedInterfaceTypes(VD);
5971 if (isTopLevelBlockPointerType(VD->getType()))
5972 RewriteBlockPointerDecl(VD);
5973 else if (VD->getType()->isFunctionPointerType()) {
5974 CheckFunctionPointerDecl(VD->getType(), VD);
5975 if (VD->getInit()) {
5976 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5977 RewriteCastExpr(CE);
5978 }
5979 }
5980 } else if (VD->getType()->isRecordType()) {
5981 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5982 if (RD->isCompleteDefinition())
5983 RewriteRecordBody(RD);
5984 }
5985 if (VD->getInit()) {
5986 GlobalVarDecl = VD;
5987 CurrentBody = VD->getInit();
5988 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5989 CurrentBody = 0;
5990 if (PropParentMap) {
5991 delete PropParentMap;
5992 PropParentMap = 0;
5993 }
5994 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5995 GlobalVarDecl = 0;
5996
5997 // This is needed for blocks.
5998 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5999 RewriteCastExpr(CE);
6000 }
6001 }
6002 break;
6003 }
6004 case Decl::TypeAlias:
6005 case Decl::Typedef: {
6006 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
6007 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
6008 RewriteBlockPointerDecl(TD);
6009 else if (TD->getUnderlyingType()->isFunctionPointerType())
6010 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00006011 else
6012 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006013 }
6014 break;
6015 }
6016 case Decl::CXXRecord:
6017 case Decl::Record: {
6018 RecordDecl *RD = cast<RecordDecl>(D);
6019 if (RD->isCompleteDefinition())
6020 RewriteRecordBody(RD);
6021 break;
6022 }
6023 default:
6024 break;
6025 }
6026 // Nothing yet.
6027}
6028
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006029/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6030/// protocol reference symbols in the for of:
6031/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6032static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6033 ObjCProtocolDecl *PDecl,
6034 std::string &Result) {
6035 // Also output .objc_protorefs$B section and its meta-data.
6036 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00006037 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006038 Result += "struct _protocol_t *";
6039 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6040 Result += PDecl->getNameAsString();
6041 Result += " = &";
6042 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6043 Result += ";\n";
6044}
6045
Fariborz Jahanian11671902012-02-07 17:11:38 +00006046void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6047 if (Diags.hasErrorOccurred())
6048 return;
6049
6050 RewriteInclude();
6051
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006052 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006053 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006054 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006055 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006056 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6057 HandleTopLevelSingleDecl(FDecl);
6058 }
6059
Fariborz Jahanian11671902012-02-07 17:11:38 +00006060 // Here's a great place to add any extra declarations that may be needed.
6061 // Write out meta data for each @protocol(<expr>).
6062 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006063 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006064 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006065 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6066 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006067
6068 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00006069
6070 if (ClassImplementation.size() || CategoryImplementation.size())
6071 RewriteImplementations();
6072
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00006073 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6074 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6075 // Write struct declaration for the class matching its ivar declarations.
6076 // Note that for modern abi, this is postponed until the end of TU
6077 // because class extensions and the implementation might declare their own
6078 // private ivars.
6079 RewriteInterfaceDecl(CDecl);
6080 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006081
Fariborz Jahanian11671902012-02-07 17:11:38 +00006082 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6083 // we are done.
6084 if (const RewriteBuffer *RewriteBuf =
6085 Rewrite.getRewriteBufferFor(MainFileID)) {
6086 //printf("Changed:\n");
6087 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6088 } else {
6089 llvm::errs() << "No changes\n";
6090 }
6091
6092 if (ClassImplementation.size() || CategoryImplementation.size() ||
6093 ProtocolExprDecls.size()) {
6094 // Rewrite Objective-c meta data*
6095 std::string ResultStr;
6096 RewriteMetaDataIntoBuffer(ResultStr);
6097 // Emit metadata.
6098 *OutFile << ResultStr;
6099 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006100 // Emit ImageInfo;
6101 {
6102 std::string ResultStr;
6103 WriteImageInfo(ResultStr);
6104 *OutFile << ResultStr;
6105 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006106 OutFile->flush();
6107}
6108
6109void RewriteModernObjC::Initialize(ASTContext &context) {
6110 InitializeCommon(context);
6111
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006112 Preamble += "#ifndef __OBJC2__\n";
6113 Preamble += "#define __OBJC2__\n";
6114 Preamble += "#endif\n";
6115
Fariborz Jahanian11671902012-02-07 17:11:38 +00006116 // declaring objc_selector outside the parameter list removes a silly
6117 // scope related warning...
6118 if (IsHeader)
6119 Preamble = "#pragma once\n";
6120 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006121 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6122 Preamble += "\n\tstruct objc_object *superClass; ";
6123 // Add a constructor for creating temporary objects.
6124 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6125 Preamble += ": object(o), superClass(s) {} ";
6126 Preamble += "\n};\n";
6127
Fariborz Jahanian11671902012-02-07 17:11:38 +00006128 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006129 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006130 // These are currently generated.
6131 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006132 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006133 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006134 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6135 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006136 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006137 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006138 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6139 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006140 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006141
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006142 // These need be generated for performance. Currently they are not,
6143 // using API calls instead.
6144 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6145 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6146 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6147
Fariborz Jahanian11671902012-02-07 17:11:38 +00006148 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006149 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6150 Preamble += "typedef struct objc_object Protocol;\n";
6151 Preamble += "#define _REWRITER_typedef_Protocol\n";
6152 Preamble += "#endif\n";
6153 if (LangOpts.MicrosoftExt) {
6154 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6155 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006156 }
6157 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006158 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006159
6160 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6161 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6162 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6163 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6164 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6165
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006166 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006167 Preamble += "(const char *);\n";
6168 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6169 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006170 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006171 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006172 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006173 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006174 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6175 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006176 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006177 Preamble += "#ifdef _WIN64\n";
6178 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6179 Preamble += "#else\n";
6180 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6181 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006182 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6183 Preamble += "struct __objcFastEnumerationState {\n\t";
6184 Preamble += "unsigned long state;\n\t";
6185 Preamble += "void **itemsPtr;\n\t";
6186 Preamble += "unsigned long *mutationsPtr;\n\t";
6187 Preamble += "unsigned long extra[5];\n};\n";
6188 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6189 Preamble += "#define __FASTENUMERATIONSTATE\n";
6190 Preamble += "#endif\n";
6191 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6192 Preamble += "struct __NSConstantStringImpl {\n";
6193 Preamble += " int *isa;\n";
6194 Preamble += " int flags;\n";
6195 Preamble += " char *str;\n";
6196 Preamble += " long length;\n";
6197 Preamble += "};\n";
6198 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6199 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6200 Preamble += "#else\n";
6201 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6202 Preamble += "#endif\n";
6203 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6204 Preamble += "#endif\n";
6205 // Blocks preamble.
6206 Preamble += "#ifndef BLOCK_IMPL\n";
6207 Preamble += "#define BLOCK_IMPL\n";
6208 Preamble += "struct __block_impl {\n";
6209 Preamble += " void *isa;\n";
6210 Preamble += " int Flags;\n";
6211 Preamble += " int Reserved;\n";
6212 Preamble += " void *FuncPtr;\n";
6213 Preamble += "};\n";
6214 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6215 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6216 Preamble += "extern \"C\" __declspec(dllexport) "
6217 "void _Block_object_assign(void *, const void *, const int);\n";
6218 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6219 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6220 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6221 Preamble += "#else\n";
6222 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6223 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6224 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6225 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6226 Preamble += "#endif\n";
6227 Preamble += "#endif\n";
6228 if (LangOpts.MicrosoftExt) {
6229 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6230 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6231 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6232 Preamble += "#define __attribute__(X)\n";
6233 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006234 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006235 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006236 Preamble += "#endif\n";
6237 Preamble += "#ifndef __block\n";
6238 Preamble += "#define __block\n";
6239 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006240 }
6241 else {
6242 Preamble += "#define __block\n";
6243 Preamble += "#define __weak\n";
6244 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006245
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006246 // Declarations required for modern objective-c array and dictionary literals.
6247 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006248 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006249 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006250 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006251 Preamble += "\tva_list marker;\n";
6252 Preamble += "\tva_start(marker, count);\n";
6253 Preamble += "\tarr = new void *[count];\n";
6254 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6255 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6256 Preamble += "\tva_end( marker );\n";
6257 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006258 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006259 Preamble += "\tdelete[] arr;\n";
6260 Preamble += " }\n";
6261 Preamble += "};\n";
6262
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006263 // Declaration required for implementation of @autoreleasepool statement.
6264 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6265 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6266 Preamble += "struct __AtAutoreleasePool {\n";
6267 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6268 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6269 Preamble += " void * atautoreleasepoolobj;\n";
6270 Preamble += "};\n";
6271
Fariborz Jahanian11671902012-02-07 17:11:38 +00006272 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6273 // as this avoids warning in any 64bit/32bit compilation model.
6274 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6275}
6276
6277/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6278/// ivar offset.
6279void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6280 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006281 Result += "__OFFSETOFIVAR__(struct ";
6282 Result += ivar->getContainingInterface()->getNameAsString();
6283 if (LangOpts.MicrosoftExt)
6284 Result += "_IMPL";
6285 Result += ", ";
6286 if (ivar->isBitField())
6287 ObjCIvarBitfieldGroupDecl(ivar, Result);
6288 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006289 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006290 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006291}
6292
6293/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6294/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006295/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006296/// char *attributes;
6297/// }
6298
6299/// struct _prop_list_t {
6300/// uint32_t entsize; // sizeof(struct _prop_t)
6301/// uint32_t count_of_properties;
6302/// struct _prop_t prop_list[count_of_properties];
6303/// }
6304
6305/// struct _protocol_t;
6306
6307/// struct _protocol_list_t {
6308/// long protocol_count; // Note, this is 32/64 bit
6309/// struct _protocol_t * protocol_list[protocol_count];
6310/// }
6311
6312/// struct _objc_method {
6313/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006314/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006315/// char *_imp;
6316/// }
6317
6318/// struct _method_list_t {
6319/// uint32_t entsize; // sizeof(struct _objc_method)
6320/// uint32_t method_count;
6321/// struct _objc_method method_list[method_count];
6322/// }
6323
6324/// struct _protocol_t {
6325/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006326/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006327/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006328/// const struct method_list_t *instance_methods;
6329/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006330/// const struct method_list_t *optionalInstanceMethods;
6331/// const struct method_list_t *optionalClassMethods;
6332/// const struct _prop_list_t * properties;
6333/// const uint32_t size; // sizeof(struct _protocol_t)
6334/// const uint32_t flags; // = 0
6335/// const char ** extendedMethodTypes;
6336/// }
6337
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006338/// struct _ivar_t {
6339/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006340/// const char *name;
6341/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006342/// uint32_t alignment;
6343/// uint32_t size;
6344/// }
6345
6346/// struct _ivar_list_t {
6347/// uint32 entsize; // sizeof(struct _ivar_t)
6348/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006349/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006350/// }
6351
6352/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006353/// uint32_t flags;
6354/// uint32_t instanceStart;
6355/// uint32_t instanceSize;
6356/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006357/// const uint8_t *ivarLayout;
6358/// const char *name;
6359/// const struct _method_list_t *baseMethods;
6360/// const struct _protocol_list_t *baseProtocols;
6361/// const struct _ivar_list_t *ivars;
6362/// const uint8_t *weakIvarLayout;
6363/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006364/// }
6365
6366/// struct _class_t {
6367/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006368/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006369/// void *cache;
6370/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006371/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006372/// }
6373
6374/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006375/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006376/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006377/// const struct _method_list_t *instance_methods;
6378/// const struct _method_list_t *class_methods;
6379/// const struct _protocol_list_t *protocols;
6380/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006381/// }
6382
6383/// MessageRefTy - LLVM for:
6384/// struct _message_ref_t {
6385/// IMP messenger;
6386/// SEL name;
6387/// };
6388
6389/// SuperMessageRefTy - LLVM for:
6390/// struct _super_message_ref_t {
6391/// SUPER_IMP messenger;
6392/// SEL name;
6393/// };
6394
Fariborz Jahanian45489622012-03-14 18:09:23 +00006395static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006396 static bool meta_data_declared = false;
6397 if (meta_data_declared)
6398 return;
6399
6400 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006401 Result += "\tconst char *name;\n";
6402 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006403 Result += "};\n";
6404
6405 Result += "\nstruct _protocol_t;\n";
6406
Fariborz Jahanian11671902012-02-07 17:11:38 +00006407 Result += "\nstruct _objc_method {\n";
6408 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006409 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006410 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006411 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006412
6413 Result += "\nstruct _protocol_t {\n";
6414 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006415 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006416 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006417 Result += "\tconst struct method_list_t *instance_methods;\n";
6418 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006419 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6420 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6421 Result += "\tconst struct _prop_list_t * properties;\n";
6422 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6423 Result += "\tconst unsigned int flags; // = 0\n";
6424 Result += "\tconst char ** extendedMethodTypes;\n";
6425 Result += "};\n";
6426
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006427 Result += "\nstruct _ivar_t {\n";
6428 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006429 Result += "\tconst char *name;\n";
6430 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006431 Result += "\tunsigned int alignment;\n";
6432 Result += "\tunsigned int size;\n";
6433 Result += "};\n";
6434
6435 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006436 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006437 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006438 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006439 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6440 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006441 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006442 Result += "\tconst unsigned char *ivarLayout;\n";
6443 Result += "\tconst char *name;\n";
6444 Result += "\tconst struct _method_list_t *baseMethods;\n";
6445 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6446 Result += "\tconst struct _ivar_list_t *ivars;\n";
6447 Result += "\tconst unsigned char *weakIvarLayout;\n";
6448 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006449 Result += "};\n";
6450
6451 Result += "\nstruct _class_t {\n";
6452 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006453 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006454 Result += "\tvoid *cache;\n";
6455 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006456 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006457 Result += "};\n";
6458
6459 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006460 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006461 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006462 Result += "\tconst struct _method_list_t *instance_methods;\n";
6463 Result += "\tconst struct _method_list_t *class_methods;\n";
6464 Result += "\tconst struct _protocol_list_t *protocols;\n";
6465 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006466 Result += "};\n";
6467
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006468 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006469 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006470 meta_data_declared = true;
6471}
6472
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006473static void Write_protocol_list_t_TypeDecl(std::string &Result,
6474 long super_protocol_count) {
6475 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6476 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6477 Result += "\tstruct _protocol_t *super_protocols[";
6478 Result += utostr(super_protocol_count); Result += "];\n";
6479 Result += "}";
6480}
6481
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006482static void Write_method_list_t_TypeDecl(std::string &Result,
6483 unsigned int method_count) {
6484 Result += "struct /*_method_list_t*/"; Result += " {\n";
6485 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6486 Result += "\tunsigned int method_count;\n";
6487 Result += "\tstruct _objc_method method_list[";
6488 Result += utostr(method_count); Result += "];\n";
6489 Result += "}";
6490}
6491
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006492static void Write__prop_list_t_TypeDecl(std::string &Result,
6493 unsigned int property_count) {
6494 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6495 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6496 Result += "\tunsigned int count_of_properties;\n";
6497 Result += "\tstruct _prop_t prop_list[";
6498 Result += utostr(property_count); Result += "];\n";
6499 Result += "}";
6500}
6501
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006502static void Write__ivar_list_t_TypeDecl(std::string &Result,
6503 unsigned int ivar_count) {
6504 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6505 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6506 Result += "\tunsigned int count;\n";
6507 Result += "\tstruct _ivar_t ivar_list[";
6508 Result += utostr(ivar_count); Result += "];\n";
6509 Result += "}";
6510}
6511
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006512static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6513 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6514 StringRef VarName,
6515 StringRef ProtocolName) {
6516 if (SuperProtocols.size() > 0) {
6517 Result += "\nstatic ";
6518 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6519 Result += " "; Result += VarName;
6520 Result += ProtocolName;
6521 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6522 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6523 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6524 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6525 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6526 Result += SuperPD->getNameAsString();
6527 if (i == e-1)
6528 Result += "\n};\n";
6529 else
6530 Result += ",\n";
6531 }
6532 }
6533}
6534
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006535static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6536 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006537 ArrayRef<ObjCMethodDecl *> Methods,
6538 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006539 StringRef TopLevelDeclName,
6540 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006541 if (Methods.size() > 0) {
6542 Result += "\nstatic ";
6543 Write_method_list_t_TypeDecl(Result, Methods.size());
6544 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006545 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006546 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6547 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6548 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6549 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6550 ObjCMethodDecl *MD = Methods[i];
6551 if (i == 0)
6552 Result += "\t{{(struct objc_selector *)\"";
6553 else
6554 Result += "\t{(struct objc_selector *)\"";
6555 Result += (MD)->getSelector().getAsString(); Result += "\"";
6556 Result += ", ";
6557 std::string MethodTypeString;
6558 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6559 Result += "\""; Result += MethodTypeString; Result += "\"";
6560 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006561 if (!MethodImpl)
6562 Result += "0";
6563 else {
6564 Result += "(void *)";
6565 Result += RewriteObj.MethodInternalNames[MD];
6566 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006567 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006568 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006569 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006570 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006571 }
6572 Result += "};\n";
6573 }
6574}
6575
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006576static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006577 ASTContext *Context, std::string &Result,
6578 ArrayRef<ObjCPropertyDecl *> Properties,
6579 const Decl *Container,
6580 StringRef VarName,
6581 StringRef ProtocolName) {
6582 if (Properties.size() > 0) {
6583 Result += "\nstatic ";
6584 Write__prop_list_t_TypeDecl(Result, Properties.size());
6585 Result += " "; Result += VarName;
6586 Result += ProtocolName;
6587 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6588 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6589 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6590 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6591 ObjCPropertyDecl *PropDecl = Properties[i];
6592 if (i == 0)
6593 Result += "\t{{\"";
6594 else
6595 Result += "\t{\"";
6596 Result += PropDecl->getName(); Result += "\",";
6597 std::string PropertyTypeString, QuotePropertyTypeString;
6598 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6599 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6600 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6601 if (i == e-1)
6602 Result += "}}\n";
6603 else
6604 Result += "},\n";
6605 }
6606 Result += "};\n";
6607 }
6608}
6609
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006610// Metadata flags
6611enum MetaDataDlags {
6612 CLS = 0x0,
6613 CLS_META = 0x1,
6614 CLS_ROOT = 0x2,
6615 OBJC2_CLS_HIDDEN = 0x10,
6616 CLS_EXCEPTION = 0x20,
6617
6618 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6619 CLS_HAS_IVAR_RELEASER = 0x40,
6620 /// class was compiled with -fobjc-arr
6621 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6622};
6623
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006624static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6625 unsigned int flags,
6626 const std::string &InstanceStart,
6627 const std::string &InstanceSize,
6628 ArrayRef<ObjCMethodDecl *>baseMethods,
6629 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6630 ArrayRef<ObjCIvarDecl *>ivars,
6631 ArrayRef<ObjCPropertyDecl *>Properties,
6632 StringRef VarName,
6633 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006634 Result += "\nstatic struct _class_ro_t ";
6635 Result += VarName; Result += ClassName;
6636 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6637 Result += "\t";
6638 Result += llvm::utostr(flags); Result += ", ";
6639 Result += InstanceStart; Result += ", ";
6640 Result += InstanceSize; Result += ", \n";
6641 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006642 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6643 if (Triple.getArch() == llvm::Triple::x86_64)
6644 // uint32_t const reserved; // only when building for 64bit targets
6645 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006646 // const uint8_t * const ivarLayout;
6647 Result += "0, \n\t";
6648 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006649 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006650 if (baseMethods.size() > 0) {
6651 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006652 if (metaclass)
6653 Result += "_OBJC_$_CLASS_METHODS_";
6654 else
6655 Result += "_OBJC_$_INSTANCE_METHODS_";
6656 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006657 Result += ",\n\t";
6658 }
6659 else
6660 Result += "0, \n\t";
6661
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006662 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006663 Result += "(const struct _objc_protocol_list *)&";
6664 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6665 Result += ",\n\t";
6666 }
6667 else
6668 Result += "0, \n\t";
6669
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006670 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006671 Result += "(const struct _ivar_list_t *)&";
6672 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6673 Result += ",\n\t";
6674 }
6675 else
6676 Result += "0, \n\t";
6677
6678 // weakIvarLayout
6679 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006680 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006681 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006682 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006683 Result += ",\n";
6684 }
6685 else
6686 Result += "0, \n";
6687
6688 Result += "};\n";
6689}
6690
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006691static void Write_class_t(ASTContext *Context, std::string &Result,
6692 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006693 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6694 bool rootClass = (!CDecl->getSuperClass());
6695 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006696
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006697 if (!rootClass) {
6698 // Find the Root class
6699 RootClass = CDecl->getSuperClass();
6700 while (RootClass->getSuperClass()) {
6701 RootClass = RootClass->getSuperClass();
6702 }
6703 }
6704
6705 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006706 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006707 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006708 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006709 if (CDecl->getImplementation())
6710 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006711 else
6712 Result += "__declspec(dllimport) ";
6713
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006714 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006715 Result += CDecl->getNameAsString();
6716 Result += ";\n";
6717 }
6718 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006719 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006720 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006721 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006722 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006723 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006724 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006725 else
6726 Result += "__declspec(dllimport) ";
6727
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006728 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006729 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006730 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006731 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006732
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006733 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006734 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006735 if (RootClass->getImplementation())
6736 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006737 else
6738 Result += "__declspec(dllimport) ";
6739
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006740 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006741 Result += VarName;
6742 Result += RootClass->getNameAsString();
6743 Result += ";\n";
6744 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006745 }
6746
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006747 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6748 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006749 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6750 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006751 if (metaclass) {
6752 if (!rootClass) {
6753 Result += "0, // &"; Result += VarName;
6754 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006755 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006756 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006757 Result += CDecl->getSuperClass()->getNameAsString();
6758 Result += ",\n\t";
6759 }
6760 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006761 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006762 Result += CDecl->getNameAsString();
6763 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006764 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006765 Result += ",\n\t";
6766 }
6767 }
6768 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006769 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006770 Result += CDecl->getNameAsString();
6771 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006772 if (!rootClass) {
6773 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006774 Result += CDecl->getSuperClass()->getNameAsString();
6775 Result += ",\n\t";
6776 }
6777 else
6778 Result += "0,\n\t";
6779 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006780 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6781 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6782 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006783 Result += "&_OBJC_METACLASS_RO_$_";
6784 else
6785 Result += "&_OBJC_CLASS_RO_$_";
6786 Result += CDecl->getNameAsString();
6787 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006788
6789 // Add static function to initialize some of the meta-data fields.
6790 // avoid doing it twice.
6791 if (metaclass)
6792 return;
6793
6794 const ObjCInterfaceDecl *SuperClass =
6795 rootClass ? CDecl : CDecl->getSuperClass();
6796
6797 Result += "static void OBJC_CLASS_SETUP_$_";
6798 Result += CDecl->getNameAsString();
6799 Result += "(void ) {\n";
6800 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6801 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006802 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006803
6804 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006805 Result += ".superclass = ";
6806 if (rootClass)
6807 Result += "&OBJC_CLASS_$_";
6808 else
6809 Result += "&OBJC_METACLASS_$_";
6810
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006811 Result += SuperClass->getNameAsString(); Result += ";\n";
6812
6813 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6814 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6815
6816 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6817 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6818 Result += CDecl->getNameAsString(); Result += ";\n";
6819
6820 if (!rootClass) {
6821 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6822 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6823 Result += SuperClass->getNameAsString(); Result += ";\n";
6824 }
6825
6826 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6827 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6828 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006829}
6830
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006831static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6832 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006833 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006834 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006835 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6836 ArrayRef<ObjCMethodDecl *> ClassMethods,
6837 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6838 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006839 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006840 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006841 // must declare an extern class object in case this class is not implemented
6842 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006843 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006844 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006845 if (ClassDecl->getImplementation())
6846 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006847 else
6848 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006849
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006850 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006851 Result += "OBJC_CLASS_$_"; Result += ClassName;
6852 Result += ";\n";
6853
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006854 Result += "\nstatic struct _category_t ";
6855 Result += "_OBJC_$_CATEGORY_";
6856 Result += ClassName; Result += "_$_"; Result += CatName;
6857 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6858 Result += "{\n";
6859 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006860 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006861 Result += ",\n";
6862 if (InstanceMethods.size() > 0) {
6863 Result += "\t(const struct _method_list_t *)&";
6864 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6865 Result += ClassName; Result += "_$_"; Result += CatName;
6866 Result += ",\n";
6867 }
6868 else
6869 Result += "\t0,\n";
6870
6871 if (ClassMethods.size() > 0) {
6872 Result += "\t(const struct _method_list_t *)&";
6873 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6874 Result += ClassName; Result += "_$_"; Result += CatName;
6875 Result += ",\n";
6876 }
6877 else
6878 Result += "\t0,\n";
6879
6880 if (RefedProtocols.size() > 0) {
6881 Result += "\t(const struct _protocol_list_t *)&";
6882 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6883 Result += ClassName; Result += "_$_"; Result += CatName;
6884 Result += ",\n";
6885 }
6886 else
6887 Result += "\t0,\n";
6888
6889 if (ClassProperties.size() > 0) {
6890 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6891 Result += ClassName; Result += "_$_"; Result += CatName;
6892 Result += ",\n";
6893 }
6894 else
6895 Result += "\t0,\n";
6896
6897 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006898
6899 // Add static function to initialize the class pointer in the category structure.
6900 Result += "static void OBJC_CATEGORY_SETUP_$_";
6901 Result += ClassDecl->getNameAsString();
6902 Result += "_$_";
6903 Result += CatName;
6904 Result += "(void ) {\n";
6905 Result += "\t_OBJC_$_CATEGORY_";
6906 Result += ClassDecl->getNameAsString();
6907 Result += "_$_";
6908 Result += CatName;
6909 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6910 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006911}
6912
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006913static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6914 ASTContext *Context, std::string &Result,
6915 ArrayRef<ObjCMethodDecl *> Methods,
6916 StringRef VarName,
6917 StringRef ProtocolName) {
6918 if (Methods.size() == 0)
6919 return;
6920
6921 Result += "\nstatic const char *";
6922 Result += VarName; Result += ProtocolName;
6923 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6924 Result += "{\n";
6925 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6926 ObjCMethodDecl *MD = Methods[i];
6927 std::string MethodTypeString, QuoteMethodTypeString;
6928 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6929 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6930 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6931 if (i == e-1)
6932 Result += "\n};\n";
6933 else {
6934 Result += ",\n";
6935 }
6936 }
6937}
6938
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006939static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6940 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006941 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006942 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006943 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006944 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6945 // this is what happens:
6946 /**
6947 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6948 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6949 Class->getVisibility() == HiddenVisibility)
6950 Visibility shoud be: HiddenVisibility;
6951 else
6952 Visibility shoud be: DefaultVisibility;
6953 */
6954
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006955 Result += "\n";
6956 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6957 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006958 if (Context->getLangOpts().MicrosoftExt)
6959 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6960
6961 if (!Context->getLangOpts().MicrosoftExt ||
6962 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006963 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006964 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006965 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006966 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006967 if (Ivars[i]->isBitField())
6968 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6969 else
6970 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006971 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6972 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006973 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6974 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006975 if (Ivars[i]->isBitField()) {
6976 // skip over rest of the ivar bitfields.
6977 SKIP_BITFIELDS(i , e, Ivars);
6978 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006979 }
6980}
6981
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006982static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6983 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006984 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006985 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006986 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006987 if (OriginalIvars.size() > 0) {
6988 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6989 SmallVector<ObjCIvarDecl *, 8> Ivars;
6990 // strip off all but the first ivar bitfield from each group of ivars.
6991 // Such ivars in the ivar list table will be replaced by their grouping struct
6992 // 'ivar'.
6993 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6994 if (OriginalIvars[i]->isBitField()) {
6995 Ivars.push_back(OriginalIvars[i]);
6996 // skip over rest of the ivar bitfields.
6997 SKIP_BITFIELDS(i , e, OriginalIvars);
6998 }
6999 else
7000 Ivars.push_back(OriginalIvars[i]);
7001 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00007002
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007003 Result += "\nstatic ";
7004 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
7005 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007006 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007007 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
7008 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
7009 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
7010 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
7011 ObjCIvarDecl *IvarDecl = Ivars[i];
7012 if (i == 0)
7013 Result += "\t{{";
7014 else
7015 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007016 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007017 if (Ivars[i]->isBitField())
7018 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7019 else
7020 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00007021 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007022
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007023 Result += "\"";
7024 if (Ivars[i]->isBitField())
7025 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7026 else
7027 Result += IvarDecl->getName();
7028 Result += "\", ";
7029
7030 QualType IVQT = IvarDecl->getType();
7031 if (IvarDecl->isBitField())
7032 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7033
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007034 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007035 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007036 IvarDecl);
7037 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7038 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7039
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007040 // FIXME. this alignment represents the host alignment and need be changed to
7041 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007042 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007043 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007044 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007045 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00007046 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007047 if (i == e-1)
7048 Result += "}}\n";
7049 else
7050 Result += "},\n";
7051 }
7052 Result += "};\n";
7053 }
7054}
7055
Fariborz Jahanian11671902012-02-07 17:11:38 +00007056/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007057void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7058 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00007059
Fariborz Jahanian11671902012-02-07 17:11:38 +00007060 // Do not synthesize the protocol more than once.
7061 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7062 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00007063 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007064
7065 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7066 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007067 // Must write out all protocol definitions in current qualifier list,
7068 // and in their nested qualifiers before writing out current definition.
7069 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7070 E = PDecl->protocol_end(); I != E; ++I)
7071 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007072
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007073 // Construct method lists.
7074 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7075 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7076 for (ObjCProtocolDecl::instmeth_iterator
7077 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7078 I != E; ++I) {
7079 ObjCMethodDecl *MD = *I;
7080 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7081 OptInstanceMethods.push_back(MD);
7082 } else {
7083 InstanceMethods.push_back(MD);
7084 }
7085 }
7086
7087 for (ObjCProtocolDecl::classmeth_iterator
7088 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7089 I != E; ++I) {
7090 ObjCMethodDecl *MD = *I;
7091 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7092 OptClassMethods.push_back(MD);
7093 } else {
7094 ClassMethods.push_back(MD);
7095 }
7096 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007097 std::vector<ObjCMethodDecl *> AllMethods;
7098 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7099 AllMethods.push_back(InstanceMethods[i]);
7100 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7101 AllMethods.push_back(ClassMethods[i]);
7102 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7103 AllMethods.push_back(OptInstanceMethods[i]);
7104 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7105 AllMethods.push_back(OptClassMethods[i]);
7106
7107 Write__extendedMethodTypes_initializer(*this, Context, Result,
7108 AllMethods,
7109 "_OBJC_PROTOCOL_METHOD_TYPES_",
7110 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007111 // Protocol's super protocol list
7112 std::vector<ObjCProtocolDecl *> SuperProtocols;
7113 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7114 E = PDecl->protocol_end(); I != E; ++I)
7115 SuperProtocols.push_back(*I);
7116
7117 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7118 "_OBJC_PROTOCOL_REFS_",
7119 PDecl->getNameAsString());
7120
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007121 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007122 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007123 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007124
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007125 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007126 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007127 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007128
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007129 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007130 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007131 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007132
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007133 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007134 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007135 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007136
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007137 // Protocol's property metadata.
7138 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7139 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7140 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007141 ProtocolProperties.push_back(*I);
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007142
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007143 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007144 /* Container */0,
7145 "_OBJC_PROTOCOL_PROPERTIES_",
7146 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007147
Fariborz Jahanian48985802012-02-08 00:50:52 +00007148 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007149 Result += "\n";
7150 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007151 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007152 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007153 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007154 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7155 Result += "\t0,\n"; // id is; is null
7156 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007157 if (SuperProtocols.size() > 0) {
7158 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7159 Result += PDecl->getNameAsString(); Result += ",\n";
7160 }
7161 else
7162 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007163 if (InstanceMethods.size() > 0) {
7164 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7165 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007166 }
7167 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007168 Result += "\t0,\n";
7169
7170 if (ClassMethods.size() > 0) {
7171 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7172 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007173 }
7174 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007175 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007176
Fariborz Jahanian48985802012-02-08 00:50:52 +00007177 if (OptInstanceMethods.size() > 0) {
7178 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7179 Result += PDecl->getNameAsString(); Result += ",\n";
7180 }
7181 else
7182 Result += "\t0,\n";
7183
7184 if (OptClassMethods.size() > 0) {
7185 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7186 Result += PDecl->getNameAsString(); Result += ",\n";
7187 }
7188 else
7189 Result += "\t0,\n";
7190
7191 if (ProtocolProperties.size() > 0) {
7192 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7193 Result += PDecl->getNameAsString(); Result += ",\n";
7194 }
7195 else
7196 Result += "\t0,\n";
7197
7198 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7199 Result += "\t0,\n";
7200
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007201 if (AllMethods.size() > 0) {
7202 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7203 Result += PDecl->getNameAsString();
7204 Result += "\n};\n";
7205 }
7206 else
7207 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007208
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007209 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007210 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007211 Result += "struct _protocol_t *";
7212 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7213 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7214 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007215
Fariborz Jahanian11671902012-02-07 17:11:38 +00007216 // Mark this protocol as having been generated.
7217 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7218 llvm_unreachable("protocol already synthesized");
7219
7220}
7221
7222void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7223 const ObjCList<ObjCProtocolDecl> &Protocols,
7224 StringRef prefix, StringRef ClassName,
7225 std::string &Result) {
7226 if (Protocols.empty()) return;
7227
7228 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007229 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007230
7231 // Output the top lovel protocol meta-data for the class.
7232 /* struct _objc_protocol_list {
7233 struct _objc_protocol_list *next;
7234 int protocol_count;
7235 struct _objc_protocol *class_protocols[];
7236 }
7237 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007238 Result += "\n";
7239 if (LangOpts.MicrosoftExt)
7240 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7241 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007242 Result += "\tstruct _objc_protocol_list *next;\n";
7243 Result += "\tint protocol_count;\n";
7244 Result += "\tstruct _objc_protocol *class_protocols[";
7245 Result += utostr(Protocols.size());
7246 Result += "];\n} _OBJC_";
7247 Result += prefix;
7248 Result += "_PROTOCOLS_";
7249 Result += ClassName;
7250 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7251 "{\n\t0, ";
7252 Result += utostr(Protocols.size());
7253 Result += "\n";
7254
7255 Result += "\t,{&_OBJC_PROTOCOL_";
7256 Result += Protocols[0]->getNameAsString();
7257 Result += " \n";
7258
7259 for (unsigned i = 1; i != Protocols.size(); i++) {
7260 Result += "\t ,&_OBJC_PROTOCOL_";
7261 Result += Protocols[i]->getNameAsString();
7262 Result += "\n";
7263 }
7264 Result += "\t }\n};\n";
7265}
7266
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007267/// hasObjCExceptionAttribute - Return true if this class or any super
7268/// class has the __objc_exception__ attribute.
7269/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7270static bool hasObjCExceptionAttribute(ASTContext &Context,
7271 const ObjCInterfaceDecl *OID) {
7272 if (OID->hasAttr<ObjCExceptionAttr>())
7273 return true;
7274 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7275 return hasObjCExceptionAttribute(Context, Super);
7276 return false;
7277}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007278
Fariborz Jahanian11671902012-02-07 17:11:38 +00007279void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7280 std::string &Result) {
7281 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7282
7283 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007284 if (CDecl->isImplicitInterfaceDecl())
7285 assert(false &&
7286 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007287
Fariborz Jahanian45489622012-03-14 18:09:23 +00007288 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007289 SmallVector<ObjCIvarDecl *, 8> IVars;
7290
7291 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7292 IVD; IVD = IVD->getNextIvar()) {
7293 // Ignore unnamed bit-fields.
7294 if (!IVD->getDeclName())
7295 continue;
7296 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007297 }
7298
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007299 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007300 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007301 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007302
7303 // Build _objc_method_list for class's instance methods if needed
7304 SmallVector<ObjCMethodDecl *, 32>
7305 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7306
7307 // If any of our property implementations have associated getters or
7308 // setters, produce metadata for them as well.
7309 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7310 PropEnd = IDecl->propimpl_end();
7311 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007312 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007313 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007314 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007315 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007316 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007317 if (!PD)
7318 continue;
7319 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007320 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007321 InstanceMethods.push_back(Getter);
7322 if (PD->isReadOnly())
7323 continue;
7324 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007325 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007326 InstanceMethods.push_back(Setter);
7327 }
7328
7329 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7330 "_OBJC_$_INSTANCE_METHODS_",
7331 IDecl->getNameAsString(), true);
7332
7333 SmallVector<ObjCMethodDecl *, 32>
7334 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7335
7336 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7337 "_OBJC_$_CLASS_METHODS_",
7338 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007339
7340 // Protocols referenced in class declaration?
7341 // Protocol's super protocol list
7342 std::vector<ObjCProtocolDecl *> RefedProtocols;
7343 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7344 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7345 E = Protocols.end();
7346 I != E; ++I) {
7347 RefedProtocols.push_back(*I);
7348 // Must write out all protocol definitions in current qualifier list,
7349 // and in their nested qualifiers before writing out current definition.
7350 RewriteObjCProtocolMetaData(*I, Result);
7351 }
7352
7353 Write_protocol_list_initializer(Context, Result,
7354 RefedProtocols,
7355 "_OBJC_CLASS_PROTOCOLS_$_",
7356 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007357
7358 // Protocol's property metadata.
7359 std::vector<ObjCPropertyDecl *> ClassProperties;
7360 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7361 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007362 ClassProperties.push_back(*I);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007363
7364 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007365 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007366 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007367 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007368
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007369
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007370 // Data for initializing _class_ro_t metaclass meta-data
7371 uint32_t flags = CLS_META;
7372 std::string InstanceSize;
7373 std::string InstanceStart;
7374
7375
7376 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7377 if (classIsHidden)
7378 flags |= OBJC2_CLS_HIDDEN;
7379
7380 if (!CDecl->getSuperClass())
7381 // class is root
7382 flags |= CLS_ROOT;
7383 InstanceSize = "sizeof(struct _class_t)";
7384 InstanceStart = InstanceSize;
7385 Write__class_ro_t_initializer(Context, Result, flags,
7386 InstanceStart, InstanceSize,
7387 ClassMethods,
7388 0,
7389 0,
7390 0,
7391 "_OBJC_METACLASS_RO_$_",
7392 CDecl->getNameAsString());
7393
7394
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007395 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007396 flags = CLS;
7397 if (classIsHidden)
7398 flags |= OBJC2_CLS_HIDDEN;
7399
7400 if (hasObjCExceptionAttribute(*Context, CDecl))
7401 flags |= CLS_EXCEPTION;
7402
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007403 if (!CDecl->getSuperClass())
7404 // class is root
7405 flags |= CLS_ROOT;
7406
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007407 InstanceSize.clear();
7408 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007409 if (!ObjCSynthesizedStructs.count(CDecl)) {
7410 InstanceSize = "0";
7411 InstanceStart = "0";
7412 }
7413 else {
7414 InstanceSize = "sizeof(struct ";
7415 InstanceSize += CDecl->getNameAsString();
7416 InstanceSize += "_IMPL)";
7417
7418 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7419 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007420 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007421 }
7422 else
7423 InstanceStart = InstanceSize;
7424 }
7425 Write__class_ro_t_initializer(Context, Result, flags,
7426 InstanceStart, InstanceSize,
7427 InstanceMethods,
7428 RefedProtocols,
7429 IVars,
7430 ClassProperties,
7431 "_OBJC_CLASS_RO_$_",
7432 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007433
7434 Write_class_t(Context, Result,
7435 "OBJC_METACLASS_$_",
7436 CDecl, /*metaclass*/true);
7437
7438 Write_class_t(Context, Result,
7439 "OBJC_CLASS_$_",
7440 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007441
7442 if (ImplementationIsNonLazy(IDecl))
7443 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007444
Fariborz Jahanian11671902012-02-07 17:11:38 +00007445}
7446
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007447void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7448 int ClsDefCount = ClassImplementation.size();
7449 if (!ClsDefCount)
7450 return;
7451 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7452 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7453 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7454 for (int i = 0; i < ClsDefCount; i++) {
7455 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7456 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7457 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7458 Result += CDecl->getName(); Result += ",\n";
7459 }
7460 Result += "};\n";
7461}
7462
Fariborz Jahanian11671902012-02-07 17:11:38 +00007463void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7464 int ClsDefCount = ClassImplementation.size();
7465 int CatDefCount = CategoryImplementation.size();
7466
7467 // For each implemented class, write out all its meta data.
7468 for (int i = 0; i < ClsDefCount; i++)
7469 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7470
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007471 RewriteClassSetupInitHook(Result);
7472
Fariborz Jahanian11671902012-02-07 17:11:38 +00007473 // For each implemented category, write out all its meta data.
7474 for (int i = 0; i < CatDefCount; i++)
7475 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7476
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007477 RewriteCategorySetupInitHook(Result);
7478
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007479 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007480 if (LangOpts.MicrosoftExt)
7481 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007482 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7483 Result += llvm::utostr(ClsDefCount); Result += "]";
7484 Result +=
7485 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7486 "regular,no_dead_strip\")))= {\n";
7487 for (int i = 0; i < ClsDefCount; i++) {
7488 Result += "\t&OBJC_CLASS_$_";
7489 Result += ClassImplementation[i]->getNameAsString();
7490 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007491 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007492 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007493
7494 if (!DefinedNonLazyClasses.empty()) {
7495 if (LangOpts.MicrosoftExt)
7496 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7497 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7498 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7499 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7500 Result += ",\n";
7501 }
7502 Result += "};\n";
7503 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007504 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007505
7506 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007507 if (LangOpts.MicrosoftExt)
7508 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007509 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7510 Result += llvm::utostr(CatDefCount); Result += "]";
7511 Result +=
7512 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7513 "regular,no_dead_strip\")))= {\n";
7514 for (int i = 0; i < CatDefCount; i++) {
7515 Result += "\t&_OBJC_$_CATEGORY_";
7516 Result +=
7517 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7518 Result += "_$_";
7519 Result += CategoryImplementation[i]->getNameAsString();
7520 Result += ",\n";
7521 }
7522 Result += "};\n";
7523 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007524
7525 if (!DefinedNonLazyCategories.empty()) {
7526 if (LangOpts.MicrosoftExt)
7527 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7528 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7529 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7530 Result += "\t&_OBJC_$_CATEGORY_";
7531 Result +=
7532 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7533 Result += "_$_";
7534 Result += DefinedNonLazyCategories[i]->getNameAsString();
7535 Result += ",\n";
7536 }
7537 Result += "};\n";
7538 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007539}
7540
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007541void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7542 if (LangOpts.MicrosoftExt)
7543 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7544
7545 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7546 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007547 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007548}
7549
Fariborz Jahanian11671902012-02-07 17:11:38 +00007550/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7551/// implementation.
7552void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7553 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007554 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007555 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7556 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007557 ObjCCategoryDecl *CDecl
7558 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007559
7560 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007561 FullCategoryName += "_$_";
7562 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007563
7564 // Build _objc_method_list for class's instance methods if needed
7565 SmallVector<ObjCMethodDecl *, 32>
7566 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7567
7568 // If any of our property implementations have associated getters or
7569 // setters, produce metadata for them as well.
7570 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7571 PropEnd = IDecl->propimpl_end();
7572 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007573 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007574 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007575 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007576 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007577 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007578 if (!PD)
7579 continue;
7580 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7581 InstanceMethods.push_back(Getter);
7582 if (PD->isReadOnly())
7583 continue;
7584 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7585 InstanceMethods.push_back(Setter);
7586 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007587
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007588 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7589 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7590 FullCategoryName, true);
7591
7592 SmallVector<ObjCMethodDecl *, 32>
7593 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7594
7595 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7596 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7597 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007598
7599 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007600 // Protocol's super protocol list
7601 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00007602 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7603 E = CDecl->protocol_end();
7604
7605 I != E; ++I) {
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007606 RefedProtocols.push_back(*I);
7607 // Must write out all protocol definitions in current qualifier list,
7608 // and in their nested qualifiers before writing out current definition.
7609 RewriteObjCProtocolMetaData(*I, Result);
7610 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007611
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007612 Write_protocol_list_initializer(Context, Result,
7613 RefedProtocols,
7614 "_OBJC_CATEGORY_PROTOCOLS_$_",
7615 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007616
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007617 // Protocol's property metadata.
7618 std::vector<ObjCPropertyDecl *> ClassProperties;
7619 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7620 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007621 ClassProperties.push_back(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007622
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007623 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007624 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007625 "_OBJC_$_PROP_LIST_",
7626 FullCategoryName);
7627
7628 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007629 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007630 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007631 InstanceMethods,
7632 ClassMethods,
7633 RefedProtocols,
7634 ClassProperties);
7635
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007636 // Determine if this category is also "non-lazy".
7637 if (ImplementationIsNonLazy(IDecl))
7638 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007639
7640}
7641
7642void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7643 int CatDefCount = CategoryImplementation.size();
7644 if (!CatDefCount)
7645 return;
7646 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7647 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7648 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7649 for (int i = 0; i < CatDefCount; i++) {
7650 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7651 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7652 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7653 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7654 Result += ClassDecl->getName();
7655 Result += "_$_";
7656 Result += CatDecl->getName();
7657 Result += ",\n";
7658 }
7659 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007660}
7661
7662// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7663/// class methods.
7664template<typename MethodIterator>
7665void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7666 MethodIterator MethodEnd,
7667 bool IsInstanceMethod,
7668 StringRef prefix,
7669 StringRef ClassName,
7670 std::string &Result) {
7671 if (MethodBegin == MethodEnd) return;
7672
7673 if (!objc_impl_method) {
7674 /* struct _objc_method {
7675 SEL _cmd;
7676 char *method_types;
7677 void *_imp;
7678 }
7679 */
7680 Result += "\nstruct _objc_method {\n";
7681 Result += "\tSEL _cmd;\n";
7682 Result += "\tchar *method_types;\n";
7683 Result += "\tvoid *_imp;\n";
7684 Result += "};\n";
7685
7686 objc_impl_method = true;
7687 }
7688
7689 // Build _objc_method_list for class's methods if needed
7690
7691 /* struct {
7692 struct _objc_method_list *next_method;
7693 int method_count;
7694 struct _objc_method method_list[];
7695 }
7696 */
7697 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007698 Result += "\n";
7699 if (LangOpts.MicrosoftExt) {
7700 if (IsInstanceMethod)
7701 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7702 else
7703 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7704 }
7705 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007706 Result += "\tstruct _objc_method_list *next_method;\n";
7707 Result += "\tint method_count;\n";
7708 Result += "\tstruct _objc_method method_list[";
7709 Result += utostr(NumMethods);
7710 Result += "];\n} _OBJC_";
7711 Result += prefix;
7712 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7713 Result += "_METHODS_";
7714 Result += ClassName;
7715 Result += " __attribute__ ((used, section (\"__OBJC, __";
7716 Result += IsInstanceMethod ? "inst" : "cls";
7717 Result += "_meth\")))= ";
7718 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7719
7720 Result += "\t,{{(SEL)\"";
7721 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7722 std::string MethodTypeString;
7723 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7724 Result += "\", \"";
7725 Result += MethodTypeString;
7726 Result += "\", (void *)";
7727 Result += MethodInternalNames[*MethodBegin];
7728 Result += "}\n";
7729 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7730 Result += "\t ,{(SEL)\"";
7731 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7732 std::string MethodTypeString;
7733 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7734 Result += "\", \"";
7735 Result += MethodTypeString;
7736 Result += "\", (void *)";
7737 Result += MethodInternalNames[*MethodBegin];
7738 Result += "}\n";
7739 }
7740 Result += "\t }\n};\n";
7741}
7742
7743Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7744 SourceRange OldRange = IV->getSourceRange();
7745 Expr *BaseExpr = IV->getBase();
7746
7747 // Rewrite the base, but without actually doing replaces.
7748 {
7749 DisableReplaceStmtScope S(*this);
7750 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7751 IV->setBase(BaseExpr);
7752 }
7753
7754 ObjCIvarDecl *D = IV->getDecl();
7755
7756 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007757
Fariborz Jahanian11671902012-02-07 17:11:38 +00007758 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7759 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007760 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007761 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7762 // lookup which class implements the instance variable.
7763 ObjCInterfaceDecl *clsDeclared = 0;
7764 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7765 clsDeclared);
7766 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7767
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007768 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007769 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007770 if (D->isBitField())
7771 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7772 else
7773 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007774
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007775 ReferencedIvars[clsDeclared].insert(D);
7776
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007777 // cast offset to "char *".
7778 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7779 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007780 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007781 BaseExpr);
7782 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7783 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007784 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007785 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7786 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007787 SourceLocation());
7788 BinaryOperator *addExpr =
7789 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7790 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007791 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007792 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007793 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7794 SourceLocation(),
7795 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007796 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007797 if (D->isBitField())
7798 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007799
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007800 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007801 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007802 RD = RD->getDefinition();
7803 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007804 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007805 ObjCContainerDecl *CDecl =
7806 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7807 // ivar in class extensions requires special treatment.
7808 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7809 CDecl = CatDecl->getClassInterface();
7810 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007811 RecName += "_IMPL";
7812 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7813 SourceLocation(), SourceLocation(),
7814 &Context->Idents.get(RecName.c_str()));
7815 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7816 unsigned UnsignedIntSize =
7817 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7818 Expr *Zero = IntegerLiteral::Create(*Context,
7819 llvm::APInt(UnsignedIntSize, 0),
7820 Context->UnsignedIntTy, SourceLocation());
7821 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7822 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7823 Zero);
7824 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7825 SourceLocation(),
7826 &Context->Idents.get(D->getNameAsString()),
7827 IvarT, 0,
7828 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007829 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007830 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7831 FD->getType(), VK_LValue,
7832 OK_Ordinary);
7833 IvarT = Context->getDecltypeType(ME, ME->getType());
7834 }
7835 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007836 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007837 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007838
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007839 castExpr = NoTypeInfoCStyleCastExpr(Context,
7840 castT,
7841 CK_BitCast,
7842 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007843
7844
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007845 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007846 VK_LValue, OK_Ordinary,
7847 SourceLocation());
7848 PE = new (Context) ParenExpr(OldRange.getBegin(),
7849 OldRange.getEnd(),
7850 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007851
7852 if (D->isBitField()) {
7853 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7854 SourceLocation(),
7855 &Context->Idents.get(D->getNameAsString()),
7856 D->getType(), 0,
7857 /*BitWidth=*/D->getBitWidth(),
7858 /*Mutable=*/true,
7859 ICIS_NoInit);
7860 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7861 FD->getType(), VK_LValue,
7862 OK_Ordinary);
7863 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007864
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007865 }
7866 else
7867 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007868 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007869
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007870 ReplaceStmtWithRange(IV, Replacement, OldRange);
7871 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007872}