blob: 01811f642adba19079366f92f73551a8bedd2e5f [file] [log] [blame]
Fariborz Jahanian64cb63a2012-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 Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
15#include "clang/Rewrite/Core/Rewriter.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000019#include "clang/AST/ParentMap.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000023#include "clang/Lex/Lexer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000024#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/OwningPtr.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000028#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000030
31using namespace clang;
32using llvm::utostr;
33
34namespace {
35 class RewriteModernObjC : public ASTConsumer {
36 protected:
37
38 enum {
39 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
40 block, ... */
41 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
42 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
43 __block variable */
44 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
45 helpers */
46 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
47 support routines */
48 BLOCK_BYREF_CURRENT_MAX = 256
49 };
50
51 enum {
52 BLOCK_NEEDS_FREE = (1 << 24),
53 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
54 BLOCK_HAS_CXX_OBJ = (1 << 26),
55 BLOCK_IS_GC = (1 << 27),
56 BLOCK_IS_GLOBAL = (1 << 28),
57 BLOCK_HAS_DESCRIPTOR = (1 << 29)
58 };
59 static const int OBJC_ABI_VERSION = 7;
60
61 Rewriter Rewrite;
62 DiagnosticsEngine &Diags;
63 const LangOptions &LangOpts;
64 ASTContext *Context;
65 SourceManager *SM;
66 TranslationUnitDecl *TUDecl;
67 FileID MainFileID;
68 const char *MainFileStart, *MainFileEnd;
69 Stmt *CurrentBody;
70 ParentMap *PropParentMap; // created lazily.
71 std::string InFileName;
72 raw_ostream* OutFile;
73 std::string Preamble;
74
75 TypeDecl *ProtocolTypeDecl;
76 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000077 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000078 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000079 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000080 // ObjC string constant support.
81 unsigned NumObjCStringLiterals;
82 VarDecl *ConstantStringClassReference;
83 RecordDecl *NSStringRecord;
84
85 // ObjC foreach break/continue generation support.
86 int BcLabelCount;
87
88 unsigned TryFinallyContainsReturnDiag;
89 // Needed for super.
90 ObjCMethodDecl *CurMethodDef;
91 RecordDecl *SuperStructDecl;
92 RecordDecl *ConstantStringDecl;
93
94 FunctionDecl *MsgSendFunctionDecl;
95 FunctionDecl *MsgSendSuperFunctionDecl;
96 FunctionDecl *MsgSendStretFunctionDecl;
97 FunctionDecl *MsgSendSuperStretFunctionDecl;
98 FunctionDecl *MsgSendFpretFunctionDecl;
99 FunctionDecl *GetClassFunctionDecl;
100 FunctionDecl *GetMetaClassFunctionDecl;
101 FunctionDecl *GetSuperClassFunctionDecl;
102 FunctionDecl *SelGetUidFunctionDecl;
103 FunctionDecl *CFStringFunctionDecl;
104 FunctionDecl *SuperContructorFunctionDecl;
105 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000106
107 /* Misc. containers needed for meta-data rewrite. */
108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000113 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000114 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000115 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
116 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
117
118 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
119 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
120
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000121 SmallVector<Stmt *, 32> Stmts;
122 SmallVector<int, 8> ObjCBcLabelNo;
123 // Remember all the @protocol(<expr>) expressions.
124 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
125
126 llvm::DenseSet<uint64_t> CopyDestroyCache;
127
128 // Block expressions.
129 SmallVector<BlockExpr *, 32> Blocks;
130 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
John McCallf4b88a42012-03-10 09:33:50 +0000133 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000134
135 // Block related declarations.
136 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
138 SmallVector<ValueDecl *, 8> BlockByRefDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
140 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
141 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
142 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
143
144 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000145 llvm::DenseMap<ObjCInterfaceDecl *,
146 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
147
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000148 // This maps an original source AST to it's rewritten form. This allows
149 // us to avoid rewriting the same node twice (which is very uncommon).
150 // This is needed to support some of the exotic property rewriting.
151 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
152
153 // Needed for header files being rewritten
154 bool IsHeader;
155 bool SilenceRewriteMacroWarning;
156 bool objc_impl_method;
157
158 bool DisableReplaceStmt;
159 class DisableReplaceStmtScope {
160 RewriteModernObjC &R;
161 bool SavedValue;
162
163 public:
164 DisableReplaceStmtScope(RewriteModernObjC &R)
165 : R(R), SavedValue(R.DisableReplaceStmt) {
166 R.DisableReplaceStmt = true;
167 }
168 ~DisableReplaceStmtScope() {
169 R.DisableReplaceStmt = SavedValue;
170 }
171 };
172 void InitializeCommon(ASTContext &context);
173
174 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000175 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000176 // Top Level Driver code.
177 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
178 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
179 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
180 if (!Class->isThisDeclarationADefinition()) {
181 RewriteForwardClassDecl(D);
182 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000183 } else {
184 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000185 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000186 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000187 }
188 }
189
190 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
191 if (!Proto->isThisDeclarationADefinition()) {
192 RewriteForwardProtocolDecl(D);
193 break;
194 }
195 }
196
197 HandleTopLevelSingleDecl(*I);
198 }
199 return true;
200 }
201 void HandleTopLevelSingleDecl(Decl *D);
202 void HandleDeclInMainFile(Decl *D);
203 RewriteModernObjC(std::string inFile, raw_ostream *OS,
204 DiagnosticsEngine &D, const LangOptions &LOpts,
205 bool silenceMacroWarn);
206
207 ~RewriteModernObjC() {}
208
209 virtual void HandleTranslationUnit(ASTContext &C);
210
211 void ReplaceStmt(Stmt *Old, Stmt *New) {
212 Stmt *ReplacingStmt = ReplacedNodes[Old];
213
214 if (ReplacingStmt)
215 return; // We can't rewrite the same node twice.
216
217 if (DisableReplaceStmt)
218 return;
219
220 // If replacement succeeded or warning disabled return with no warning.
221 if (!Rewrite.ReplaceStmt(Old, New)) {
222 ReplacedNodes[Old] = New;
223 return;
224 }
225 if (SilenceRewriteMacroWarning)
226 return;
227 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
228 << Old->getSourceRange();
229 }
230
231 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
232 if (DisableReplaceStmt)
233 return;
234
235 // Measure the old text.
236 int Size = Rewrite.getRangeSize(SrcRange);
237 if (Size == -1) {
238 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
239 << Old->getSourceRange();
240 return;
241 }
242 // Get the new text.
243 std::string SStr;
244 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000245 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000246 const std::string &Str = S.str();
247
248 // If replacement succeeded or warning disabled return with no warning.
249 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
250 ReplacedNodes[Old] = New;
251 return;
252 }
253 if (SilenceRewriteMacroWarning)
254 return;
255 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
256 << Old->getSourceRange();
257 }
258
259 void InsertText(SourceLocation Loc, StringRef Str,
260 bool InsertAfter = true) {
261 // If insertion succeeded or warning disabled return with no warning.
262 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
263 SilenceRewriteMacroWarning)
264 return;
265
266 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
267 }
268
269 void ReplaceText(SourceLocation Start, unsigned OrigLength,
270 StringRef Str) {
271 // If removal succeeded or warning disabled return with no warning.
272 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
273 SilenceRewriteMacroWarning)
274 return;
275
276 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
277 }
278
279 // Syntactic Rewriting.
280 void RewriteRecordBody(RecordDecl *RD);
281 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000282 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000283 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
284 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000285 void RewriteForwardClassDecl(DeclGroupRef D);
286 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
287 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
288 const std::string &typedefString);
289 void RewriteImplementations();
290 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
291 ObjCImplementationDecl *IMD,
292 ObjCCategoryImplDecl *CID);
293 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
294 void RewriteImplementationDecl(Decl *Dcl);
295 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
296 ObjCMethodDecl *MDecl, std::string &ResultStr);
297 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
298 const FunctionType *&FPRetType);
299 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
300 ValueDecl *VD, bool def=false);
301 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
302 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
303 void RewriteForwardProtocolDecl(DeclGroupRef D);
304 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
305 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
306 void RewriteProperty(ObjCPropertyDecl *prop);
307 void RewriteFunctionDecl(FunctionDecl *FD);
308 void RewriteBlockPointerType(std::string& Str, QualType Type);
309 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000310 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000311 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
312 void RewriteTypeOfDecl(VarDecl *VD);
313 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000314
315 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000316
317 // Expression Rewriting.
318 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
319 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
320 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
321 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
322 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
323 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
324 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000325 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000326 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000327 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000328 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000329 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000330 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000331 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000332 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
333 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
334 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
335 SourceLocation OrigEnd);
336 Stmt *RewriteBreakStmt(BreakStmt *S);
337 Stmt *RewriteContinueStmt(ContinueStmt *S);
338 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000339 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000340 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000341
342 // Block rewriting.
343 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
344
345 // Block specific rewrite rules.
346 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000347 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000348 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000349 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
350 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
351
352 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
353 std::string &Result);
354
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000355 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000356 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000357 bool &IsNamedDefinition);
358 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
359 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000360
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000361 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
362
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000363 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
364 std::string &Result);
365
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000366 virtual void Initialize(ASTContext &context);
367
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000368 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000369 // rewriting routines on the new ASTs.
370 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
371 Expr **args, unsigned nargs,
372 SourceLocation StartLoc=SourceLocation(),
373 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000374
375 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
376 QualType msgSendType,
377 QualType returnType,
378 SmallVectorImpl<QualType> &ArgTypes,
379 SmallVectorImpl<Expr*> &MsgExprs,
380 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000381
382 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
383 SourceLocation StartLoc=SourceLocation(),
384 SourceLocation EndLoc=SourceLocation());
385
386 void SynthCountByEnumWithState(std::string &buf);
387 void SynthMsgSendFunctionDecl();
388 void SynthMsgSendSuperFunctionDecl();
389 void SynthMsgSendStretFunctionDecl();
390 void SynthMsgSendFpretFunctionDecl();
391 void SynthMsgSendSuperStretFunctionDecl();
392 void SynthGetClassFunctionDecl();
393 void SynthGetMetaClassFunctionDecl();
394 void SynthGetSuperClassFunctionDecl();
395 void SynthSelGetUidFunctionDecl();
396 void SynthSuperContructorFunctionDecl();
397
398 // Rewriting metadata
399 template<typename MethodIterator>
400 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
401 MethodIterator MethodEnd,
402 bool IsInstanceMethod,
403 StringRef prefix,
404 StringRef ClassName,
405 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000406 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
407 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000408 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000409 const ObjCList<ObjCProtocolDecl> &Prots,
410 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000411 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000412 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000413 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000414
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000415 void RewriteMetaDataIntoBuffer(std::string &Result);
416 void WriteImageInfo(std::string &Result);
417 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000418 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000419 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000420
421 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000422 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000423 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000424 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000425
426
427 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
428 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
429 StringRef funcName, std::string Tag);
430 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
431 StringRef funcName, std::string Tag);
432 std::string SynthesizeBlockImpl(BlockExpr *CE,
433 std::string Tag, std::string Desc);
434 std::string SynthesizeBlockDescriptor(std::string DescTag,
435 std::string ImplTag,
436 int i, StringRef funcName,
437 unsigned hasCopy);
438 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
439 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
440 StringRef FunName);
441 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
442 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000443 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000444
445 // Misc. helper routines.
446 QualType getProtocolType();
447 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000448 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
449 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
450 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
451
452 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
453 void CollectBlockDeclRefInfo(BlockExpr *Exp);
454 void GetBlockDeclRefExprs(Stmt *S);
455 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000456 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000457 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
458
459 // We avoid calling Type::isBlockPointerType(), since it operates on the
460 // canonical type. We only care if the top-level type is a closure pointer.
461 bool isTopLevelBlockPointerType(QualType T) {
462 return isa<BlockPointerType>(T);
463 }
464
465 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
466 /// to a function pointer type and upon success, returns true; false
467 /// otherwise.
468 bool convertBlockPointerToFunctionPointer(QualType &T) {
469 if (isTopLevelBlockPointerType(T)) {
470 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
471 T = Context->getPointerType(BPT->getPointeeType());
472 return true;
473 }
474 return false;
475 }
476
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000477 bool convertObjCTypeToCStyleType(QualType &T);
478
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000479 bool needToScanForQualifiers(QualType T);
480 QualType getSuperStructType();
481 QualType getConstantStringStructType();
482 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
483 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
484
485 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000486 if (T->isObjCQualifiedIdType()) {
487 bool isConst = T.isConstQualified();
488 T = isConst ? Context->getObjCIdType().withConst()
489 : Context->getObjCIdType();
490 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000491 else if (T->isObjCQualifiedClassType())
492 T = Context->getObjCClassType();
493 else if (T->isObjCObjectPointerType() &&
494 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
495 if (const ObjCObjectPointerType * OBJPT =
496 T->getAsObjCInterfacePointerType()) {
497 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
498 T = QualType(IFaceT, 0);
499 T = Context->getPointerType(T);
500 }
501 }
502 }
503
504 // FIXME: This predicate seems like it would be useful to add to ASTContext.
505 bool isObjCType(QualType T) {
506 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
507 return false;
508
509 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
510
511 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
512 OCT == Context->getCanonicalType(Context->getObjCClassType()))
513 return true;
514
515 if (const PointerType *PT = OCT->getAs<PointerType>()) {
516 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
517 PT->getPointeeType()->isObjCQualifiedIdType())
518 return true;
519 }
520 return false;
521 }
522 bool PointerTypeTakesAnyBlockArguments(QualType QT);
523 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
524 void GetExtentOfArgList(const char *Name, const char *&LParen,
525 const char *&RParen);
526
527 void QuoteDoublequotes(std::string &From, std::string &To) {
528 for (unsigned i = 0; i < From.length(); i++) {
529 if (From[i] == '"')
530 To += "\\\"";
531 else
532 To += From[i];
533 }
534 }
535
536 QualType getSimpleFunctionType(QualType result,
537 const QualType *args,
538 unsigned numArgs,
539 bool variadic = false) {
540 if (result == Context->getObjCInstanceType())
541 result = Context->getObjCIdType();
542 FunctionProtoType::ExtProtoInfo fpi;
543 fpi.Variadic = variadic;
544 return Context->getFunctionType(result, args, numArgs, fpi);
545 }
546
547 // Helper function: create a CStyleCastExpr with trivial type source info.
548 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
549 CastKind Kind, Expr *E) {
550 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
551 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
552 SourceLocation(), SourceLocation());
553 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000554
555 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
556 IdentifierInfo* II = &Context->Idents.get("load");
557 Selector LoadSel = Context->Selectors.getSelector(0, &II);
558 return OD->getClassMethod(LoadSel) != 0;
559 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000560 };
561
562}
563
564void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
565 NamedDecl *D) {
566 if (const FunctionProtoType *fproto
567 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
568 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
569 E = fproto->arg_type_end(); I && (I != E); ++I)
570 if (isTopLevelBlockPointerType(*I)) {
571 // All the args are checked/rewritten. Don't call twice!
572 RewriteBlockPointerDecl(D);
573 break;
574 }
575 }
576}
577
578void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
579 const PointerType *PT = funcType->getAs<PointerType>();
580 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
581 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
582}
583
584static bool IsHeaderFile(const std::string &Filename) {
585 std::string::size_type DotPos = Filename.rfind('.');
586
587 if (DotPos == std::string::npos) {
588 // no file extension
589 return false;
590 }
591
592 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
593 // C header: .h
594 // C++ header: .hh or .H;
595 return Ext == "h" || Ext == "hh" || Ext == "H";
596}
597
598RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
599 DiagnosticsEngine &D, const LangOptions &LOpts,
600 bool silenceMacroWarn)
601 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
602 SilenceRewriteMacroWarning(silenceMacroWarn) {
603 IsHeader = IsHeaderFile(inFile);
604 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
605 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000606 // FIXME. This should be an error. But if block is not called, it is OK. And it
607 // may break including some headers.
608 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
609 "rewriting block literal declared in global scope is not implemented");
610
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000611 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
612 DiagnosticsEngine::Warning,
613 "rewriter doesn't support user-specified control flow semantics "
614 "for @try/@finally (code may not execute properly)");
615}
616
617ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
618 raw_ostream* OS,
619 DiagnosticsEngine &Diags,
620 const LangOptions &LOpts,
621 bool SilenceRewriteMacroWarning) {
622 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
623}
624
625void RewriteModernObjC::InitializeCommon(ASTContext &context) {
626 Context = &context;
627 SM = &Context->getSourceManager();
628 TUDecl = Context->getTranslationUnitDecl();
629 MsgSendFunctionDecl = 0;
630 MsgSendSuperFunctionDecl = 0;
631 MsgSendStretFunctionDecl = 0;
632 MsgSendSuperStretFunctionDecl = 0;
633 MsgSendFpretFunctionDecl = 0;
634 GetClassFunctionDecl = 0;
635 GetMetaClassFunctionDecl = 0;
636 GetSuperClassFunctionDecl = 0;
637 SelGetUidFunctionDecl = 0;
638 CFStringFunctionDecl = 0;
639 ConstantStringClassReference = 0;
640 NSStringRecord = 0;
641 CurMethodDef = 0;
642 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000643 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000644 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000645 SuperStructDecl = 0;
646 ProtocolTypeDecl = 0;
647 ConstantStringDecl = 0;
648 BcLabelCount = 0;
649 SuperContructorFunctionDecl = 0;
650 NumObjCStringLiterals = 0;
651 PropParentMap = 0;
652 CurrentBody = 0;
653 DisableReplaceStmt = false;
654 objc_impl_method = false;
655
656 // Get the ID and start/end of the main file.
657 MainFileID = SM->getMainFileID();
658 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
659 MainFileStart = MainBuf->getBufferStart();
660 MainFileEnd = MainBuf->getBufferEnd();
661
David Blaikie4e4d0842012-03-11 07:00:24 +0000662 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000663}
664
665//===----------------------------------------------------------------------===//
666// Top Level Driver Code
667//===----------------------------------------------------------------------===//
668
669void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
670 if (Diags.hasErrorOccurred())
671 return;
672
673 // Two cases: either the decl could be in the main file, or it could be in a
674 // #included file. If the former, rewrite it now. If the later, check to see
675 // if we rewrote the #include/#import.
676 SourceLocation Loc = D->getLocation();
677 Loc = SM->getExpansionLoc(Loc);
678
679 // If this is for a builtin, ignore it.
680 if (Loc.isInvalid()) return;
681
682 // Look for built-in declarations that we need to refer during the rewrite.
683 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
684 RewriteFunctionDecl(FD);
685 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
686 // declared in <Foundation/NSString.h>
687 if (FVD->getName() == "_NSConstantStringClassReference") {
688 ConstantStringClassReference = FVD;
689 return;
690 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000691 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
692 RewriteCategoryDecl(CD);
693 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
694 if (PD->isThisDeclarationADefinition())
695 RewriteProtocolDecl(PD);
696 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000697 // FIXME. This will not work in all situations and leaving it out
698 // is harmless.
699 // RewriteLinkageSpec(LSD);
700
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000701 // Recurse into linkage specifications
702 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
703 DIEnd = LSD->decls_end();
704 DI != DIEnd; ) {
705 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
706 if (!IFace->isThisDeclarationADefinition()) {
707 SmallVector<Decl *, 8> DG;
708 SourceLocation StartLoc = IFace->getLocStart();
709 do {
710 if (isa<ObjCInterfaceDecl>(*DI) &&
711 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
712 StartLoc == (*DI)->getLocStart())
713 DG.push_back(*DI);
714 else
715 break;
716
717 ++DI;
718 } while (DI != DIEnd);
719 RewriteForwardClassDecl(DG);
720 continue;
721 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000722 else {
723 // Keep track of all interface declarations seen.
724 ObjCInterfacesSeen.push_back(IFace);
725 ++DI;
726 continue;
727 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000728 }
729
730 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
731 if (!Proto->isThisDeclarationADefinition()) {
732 SmallVector<Decl *, 8> DG;
733 SourceLocation StartLoc = Proto->getLocStart();
734 do {
735 if (isa<ObjCProtocolDecl>(*DI) &&
736 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
737 StartLoc == (*DI)->getLocStart())
738 DG.push_back(*DI);
739 else
740 break;
741
742 ++DI;
743 } while (DI != DIEnd);
744 RewriteForwardProtocolDecl(DG);
745 continue;
746 }
747 }
748
749 HandleTopLevelSingleDecl(*DI);
750 ++DI;
751 }
752 }
753 // If we have a decl in the main file, see if we should rewrite it.
754 if (SM->isFromMainFile(Loc))
755 return HandleDeclInMainFile(D);
756}
757
758//===----------------------------------------------------------------------===//
759// Syntactic (non-AST) Rewriting Code
760//===----------------------------------------------------------------------===//
761
762void RewriteModernObjC::RewriteInclude() {
763 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
764 StringRef MainBuf = SM->getBufferData(MainFileID);
765 const char *MainBufStart = MainBuf.begin();
766 const char *MainBufEnd = MainBuf.end();
767 size_t ImportLen = strlen("import");
768
769 // Loop over the whole file, looking for includes.
770 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
771 if (*BufPtr == '#') {
772 if (++BufPtr == MainBufEnd)
773 return;
774 while (*BufPtr == ' ' || *BufPtr == '\t')
775 if (++BufPtr == MainBufEnd)
776 return;
777 if (!strncmp(BufPtr, "import", ImportLen)) {
778 // replace import with include
779 SourceLocation ImportLoc =
780 LocStart.getLocWithOffset(BufPtr-MainBufStart);
781 ReplaceText(ImportLoc, ImportLen, "include");
782 BufPtr += ImportLen;
783 }
784 }
785 }
786}
787
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000788static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
789 ObjCIvarDecl *IvarDecl, std::string &Result) {
790 Result += "OBJC_IVAR_$_";
791 Result += IDecl->getName();
792 Result += "$";
793 Result += IvarDecl->getName();
794}
795
796std::string
797RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
798 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
799
800 // Build name of symbol holding ivar offset.
801 std::string IvarOffsetName;
802 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
803
804
805 std::string S = "(*(";
806 QualType IvarT = D->getType();
807
808 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
809 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
810 RD = RD->getDefinition();
811 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
812 // decltype(((Foo_IMPL*)0)->bar) *
813 ObjCContainerDecl *CDecl =
814 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
815 // ivar in class extensions requires special treatment.
816 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
817 CDecl = CatDecl->getClassInterface();
818 std::string RecName = CDecl->getName();
819 RecName += "_IMPL";
820 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
821 SourceLocation(), SourceLocation(),
822 &Context->Idents.get(RecName.c_str()));
823 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
824 unsigned UnsignedIntSize =
825 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
826 Expr *Zero = IntegerLiteral::Create(*Context,
827 llvm::APInt(UnsignedIntSize, 0),
828 Context->UnsignedIntTy, SourceLocation());
829 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
830 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
831 Zero);
832 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
833 SourceLocation(),
834 &Context->Idents.get(D->getNameAsString()),
835 IvarT, 0,
836 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000837 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000838 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
839 FD->getType(), VK_LValue,
840 OK_Ordinary);
841 IvarT = Context->getDecltypeType(ME, ME->getType());
842 }
843 }
844 convertObjCTypeToCStyleType(IvarT);
845 QualType castT = Context->getPointerType(IvarT);
846 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
847 S += TypeString;
848 S += ")";
849
850 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
851 S += "((char *)self + ";
852 S += IvarOffsetName;
853 S += "))";
854 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000855 return S;
856}
857
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000858/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
859/// been found in the class implementation. In this case, it must be synthesized.
860static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
861 ObjCPropertyDecl *PD,
862 bool getter) {
863 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
864 : !IMP->getInstanceMethod(PD->getSetterName());
865
866}
867
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000868void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
869 ObjCImplementationDecl *IMD,
870 ObjCCategoryImplDecl *CID) {
871 static bool objcGetPropertyDefined = false;
872 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000873 SourceLocation startGetterSetterLoc;
874
875 if (PID->getLocStart().isValid()) {
876 SourceLocation startLoc = PID->getLocStart();
877 InsertText(startLoc, "// ");
878 const char *startBuf = SM->getCharacterData(startLoc);
879 assert((*startBuf == '@') && "bogus @synthesize location");
880 const char *semiBuf = strchr(startBuf, ';');
881 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
882 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
883 }
884 else
885 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000886
887 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
888 return; // FIXME: is this correct?
889
890 // Generate the 'getter' function.
891 ObjCPropertyDecl *PD = PID->getPropertyDecl();
892 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
893
894 if (!OID)
895 return;
896 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000897 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000898 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
899 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
900 ObjCPropertyDecl::OBJC_PR_copy));
901 std::string Getr;
902 if (GenGetProperty && !objcGetPropertyDefined) {
903 objcGetPropertyDefined = true;
904 // FIXME. Is this attribute correct in all cases?
905 Getr = "\nextern \"C\" __declspec(dllimport) "
906 "id objc_getProperty(id, SEL, long, bool);\n";
907 }
908 RewriteObjCMethodDecl(OID->getContainingInterface(),
909 PD->getGetterMethodDecl(), Getr);
910 Getr += "{ ";
911 // Synthesize an explicit cast to gain access to the ivar.
912 // See objc-act.c:objc_synthesize_new_getter() for details.
913 if (GenGetProperty) {
914 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
915 Getr += "typedef ";
916 const FunctionType *FPRetType = 0;
917 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
918 FPRetType);
919 Getr += " _TYPE";
920 if (FPRetType) {
921 Getr += ")"; // close the precedence "scope" for "*".
922
923 // Now, emit the argument types (if any).
924 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
925 Getr += "(";
926 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
927 if (i) Getr += ", ";
928 std::string ParamStr = FT->getArgType(i).getAsString(
929 Context->getPrintingPolicy());
930 Getr += ParamStr;
931 }
932 if (FT->isVariadic()) {
933 if (FT->getNumArgs()) Getr += ", ";
934 Getr += "...";
935 }
936 Getr += ")";
937 } else
938 Getr += "()";
939 }
940 Getr += ";\n";
941 Getr += "return (_TYPE)";
942 Getr += "objc_getProperty(self, _cmd, ";
943 RewriteIvarOffsetComputation(OID, Getr);
944 Getr += ", 1)";
945 }
946 else
947 Getr += "return " + getIvarAccessString(OID);
948 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000949 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000950 }
951
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000952 if (PD->isReadOnly() ||
953 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000954 return;
955
956 // Generate the 'setter' function.
957 std::string Setr;
958 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
959 ObjCPropertyDecl::OBJC_PR_copy);
960 if (GenSetProperty && !objcSetPropertyDefined) {
961 objcSetPropertyDefined = true;
962 // FIXME. Is this attribute correct in all cases?
963 Setr = "\nextern \"C\" __declspec(dllimport) "
964 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
965 }
966
967 RewriteObjCMethodDecl(OID->getContainingInterface(),
968 PD->getSetterMethodDecl(), Setr);
969 Setr += "{ ";
970 // Synthesize an explicit cast to initialize the ivar.
971 // See objc-act.c:objc_synthesize_new_setter() for details.
972 if (GenSetProperty) {
973 Setr += "objc_setProperty (self, _cmd, ";
974 RewriteIvarOffsetComputation(OID, Setr);
975 Setr += ", (id)";
976 Setr += PD->getName();
977 Setr += ", ";
978 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
979 Setr += "0, ";
980 else
981 Setr += "1, ";
982 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
983 Setr += "1)";
984 else
985 Setr += "0)";
986 }
987 else {
988 Setr += getIvarAccessString(OID) + " = ";
989 Setr += PD->getName();
990 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000991 Setr += "; }\n";
992 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000993}
994
995static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
996 std::string &typedefString) {
997 typedefString += "#ifndef _REWRITER_typedef_";
998 typedefString += ForwardDecl->getNameAsString();
999 typedefString += "\n";
1000 typedefString += "#define _REWRITER_typedef_";
1001 typedefString += ForwardDecl->getNameAsString();
1002 typedefString += "\n";
1003 typedefString += "typedef struct objc_object ";
1004 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001005 // typedef struct { } _objc_exc_Classname;
1006 typedefString += ";\ntypedef struct {} _objc_exc_";
1007 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001008 typedefString += ";\n#endif\n";
1009}
1010
1011void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1012 const std::string &typedefString) {
1013 SourceLocation startLoc = ClassDecl->getLocStart();
1014 const char *startBuf = SM->getCharacterData(startLoc);
1015 const char *semiPtr = strchr(startBuf, ';');
1016 // Replace the @class with typedefs corresponding to the classes.
1017 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1018}
1019
1020void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1021 std::string typedefString;
1022 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1023 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1024 if (I == D.begin()) {
1025 // Translate to typedef's that forward reference structs with the same name
1026 // as the class. As a convenience, we include the original declaration
1027 // as a comment.
1028 typedefString += "// @class ";
1029 typedefString += ForwardDecl->getNameAsString();
1030 typedefString += ";\n";
1031 }
1032 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1033 }
1034 DeclGroupRef::iterator I = D.begin();
1035 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1036}
1037
1038void RewriteModernObjC::RewriteForwardClassDecl(
1039 const llvm::SmallVector<Decl*, 8> &D) {
1040 std::string typedefString;
1041 for (unsigned i = 0; i < D.size(); i++) {
1042 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1043 if (i == 0) {
1044 typedefString += "// @class ";
1045 typedefString += ForwardDecl->getNameAsString();
1046 typedefString += ";\n";
1047 }
1048 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1049 }
1050 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1051}
1052
1053void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1054 // When method is a synthesized one, such as a getter/setter there is
1055 // nothing to rewrite.
1056 if (Method->isImplicit())
1057 return;
1058 SourceLocation LocStart = Method->getLocStart();
1059 SourceLocation LocEnd = Method->getLocEnd();
1060
1061 if (SM->getExpansionLineNumber(LocEnd) >
1062 SM->getExpansionLineNumber(LocStart)) {
1063 InsertText(LocStart, "#if 0\n");
1064 ReplaceText(LocEnd, 1, ";\n#endif\n");
1065 } else {
1066 InsertText(LocStart, "// ");
1067 }
1068}
1069
1070void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1071 SourceLocation Loc = prop->getAtLoc();
1072
1073 ReplaceText(Loc, 0, "// ");
1074 // FIXME: handle properties that are declared across multiple lines.
1075}
1076
1077void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1078 SourceLocation LocStart = CatDecl->getLocStart();
1079
1080 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001081 if (CatDecl->getIvarRBraceLoc().isValid()) {
1082 ReplaceText(LocStart, 1, "/** ");
1083 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1084 }
1085 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001086 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001087 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001088
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001089 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1090 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001091 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001092
1093 for (ObjCCategoryDecl::instmeth_iterator
1094 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1095 I != E; ++I)
1096 RewriteMethodDeclaration(*I);
1097 for (ObjCCategoryDecl::classmeth_iterator
1098 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1099 I != E; ++I)
1100 RewriteMethodDeclaration(*I);
1101
1102 // Lastly, comment out the @end.
1103 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1104 strlen("@end"), "/* @end */");
1105}
1106
1107void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1108 SourceLocation LocStart = PDecl->getLocStart();
1109 assert(PDecl->isThisDeclarationADefinition());
1110
1111 // FIXME: handle protocol headers that are declared across multiple lines.
1112 ReplaceText(LocStart, 0, "// ");
1113
1114 for (ObjCProtocolDecl::instmeth_iterator
1115 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1116 I != E; ++I)
1117 RewriteMethodDeclaration(*I);
1118 for (ObjCProtocolDecl::classmeth_iterator
1119 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1120 I != E; ++I)
1121 RewriteMethodDeclaration(*I);
1122
1123 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1124 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001125 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001126
1127 // Lastly, comment out the @end.
1128 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1129 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1130
1131 // Must comment out @optional/@required
1132 const char *startBuf = SM->getCharacterData(LocStart);
1133 const char *endBuf = SM->getCharacterData(LocEnd);
1134 for (const char *p = startBuf; p < endBuf; p++) {
1135 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1136 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1137 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1138
1139 }
1140 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1141 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1142 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1143
1144 }
1145 }
1146}
1147
1148void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1149 SourceLocation LocStart = (*D.begin())->getLocStart();
1150 if (LocStart.isInvalid())
1151 llvm_unreachable("Invalid SourceLocation");
1152 // FIXME: handle forward protocol that are declared across multiple lines.
1153 ReplaceText(LocStart, 0, "// ");
1154}
1155
1156void
1157RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1158 SourceLocation LocStart = DG[0]->getLocStart();
1159 if (LocStart.isInvalid())
1160 llvm_unreachable("Invalid SourceLocation");
1161 // FIXME: handle forward protocol that are declared across multiple lines.
1162 ReplaceText(LocStart, 0, "// ");
1163}
1164
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001165void
1166RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1167 SourceLocation LocStart = LSD->getExternLoc();
1168 if (LocStart.isInvalid())
1169 llvm_unreachable("Invalid extern SourceLocation");
1170
1171 ReplaceText(LocStart, 0, "// ");
1172 if (!LSD->hasBraces())
1173 return;
1174 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1175 SourceLocation LocRBrace = LSD->getRBraceLoc();
1176 if (LocRBrace.isInvalid())
1177 llvm_unreachable("Invalid rbrace SourceLocation");
1178 ReplaceText(LocRBrace, 0, "// ");
1179}
1180
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001181void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1182 const FunctionType *&FPRetType) {
1183 if (T->isObjCQualifiedIdType())
1184 ResultStr += "id";
1185 else if (T->isFunctionPointerType() ||
1186 T->isBlockPointerType()) {
1187 // needs special handling, since pointer-to-functions have special
1188 // syntax (where a decaration models use).
1189 QualType retType = T;
1190 QualType PointeeTy;
1191 if (const PointerType* PT = retType->getAs<PointerType>())
1192 PointeeTy = PT->getPointeeType();
1193 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1194 PointeeTy = BPT->getPointeeType();
1195 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1196 ResultStr += FPRetType->getResultType().getAsString(
1197 Context->getPrintingPolicy());
1198 ResultStr += "(*";
1199 }
1200 } else
1201 ResultStr += T.getAsString(Context->getPrintingPolicy());
1202}
1203
1204void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1205 ObjCMethodDecl *OMD,
1206 std::string &ResultStr) {
1207 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1208 const FunctionType *FPRetType = 0;
1209 ResultStr += "\nstatic ";
1210 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1211 ResultStr += " ";
1212
1213 // Unique method name
1214 std::string NameStr;
1215
1216 if (OMD->isInstanceMethod())
1217 NameStr += "_I_";
1218 else
1219 NameStr += "_C_";
1220
1221 NameStr += IDecl->getNameAsString();
1222 NameStr += "_";
1223
1224 if (ObjCCategoryImplDecl *CID =
1225 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1226 NameStr += CID->getNameAsString();
1227 NameStr += "_";
1228 }
1229 // Append selector names, replacing ':' with '_'
1230 {
1231 std::string selString = OMD->getSelector().getAsString();
1232 int len = selString.size();
1233 for (int i = 0; i < len; i++)
1234 if (selString[i] == ':')
1235 selString[i] = '_';
1236 NameStr += selString;
1237 }
1238 // Remember this name for metadata emission
1239 MethodInternalNames[OMD] = NameStr;
1240 ResultStr += NameStr;
1241
1242 // Rewrite arguments
1243 ResultStr += "(";
1244
1245 // invisible arguments
1246 if (OMD->isInstanceMethod()) {
1247 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1248 selfTy = Context->getPointerType(selfTy);
1249 if (!LangOpts.MicrosoftExt) {
1250 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1251 ResultStr += "struct ";
1252 }
1253 // When rewriting for Microsoft, explicitly omit the structure name.
1254 ResultStr += IDecl->getNameAsString();
1255 ResultStr += " *";
1256 }
1257 else
1258 ResultStr += Context->getObjCClassType().getAsString(
1259 Context->getPrintingPolicy());
1260
1261 ResultStr += " self, ";
1262 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1263 ResultStr += " _cmd";
1264
1265 // Method arguments.
1266 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1267 E = OMD->param_end(); PI != E; ++PI) {
1268 ParmVarDecl *PDecl = *PI;
1269 ResultStr += ", ";
1270 if (PDecl->getType()->isObjCQualifiedIdType()) {
1271 ResultStr += "id ";
1272 ResultStr += PDecl->getNameAsString();
1273 } else {
1274 std::string Name = PDecl->getNameAsString();
1275 QualType QT = PDecl->getType();
1276 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001277 (void)convertBlockPointerToFunctionPointer(QT);
1278 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001279 ResultStr += Name;
1280 }
1281 }
1282 if (OMD->isVariadic())
1283 ResultStr += ", ...";
1284 ResultStr += ") ";
1285
1286 if (FPRetType) {
1287 ResultStr += ")"; // close the precedence "scope" for "*".
1288
1289 // Now, emit the argument types (if any).
1290 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1291 ResultStr += "(";
1292 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1293 if (i) ResultStr += ", ";
1294 std::string ParamStr = FT->getArgType(i).getAsString(
1295 Context->getPrintingPolicy());
1296 ResultStr += ParamStr;
1297 }
1298 if (FT->isVariadic()) {
1299 if (FT->getNumArgs()) ResultStr += ", ";
1300 ResultStr += "...";
1301 }
1302 ResultStr += ")";
1303 } else {
1304 ResultStr += "()";
1305 }
1306 }
1307}
1308void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1309 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1310 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1311
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001312 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001313 if (IMD->getIvarRBraceLoc().isValid()) {
1314 ReplaceText(IMD->getLocStart(), 1, "/** ");
1315 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001316 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001317 else {
1318 InsertText(IMD->getLocStart(), "// ");
1319 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001320 }
1321 else
1322 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001323
1324 for (ObjCCategoryImplDecl::instmeth_iterator
1325 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1326 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1327 I != E; ++I) {
1328 std::string ResultStr;
1329 ObjCMethodDecl *OMD = *I;
1330 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1331 SourceLocation LocStart = OMD->getLocStart();
1332 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1333
1334 const char *startBuf = SM->getCharacterData(LocStart);
1335 const char *endBuf = SM->getCharacterData(LocEnd);
1336 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1337 }
1338
1339 for (ObjCCategoryImplDecl::classmeth_iterator
1340 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1341 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1342 I != E; ++I) {
1343 std::string ResultStr;
1344 ObjCMethodDecl *OMD = *I;
1345 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1346 SourceLocation LocStart = OMD->getLocStart();
1347 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1348
1349 const char *startBuf = SM->getCharacterData(LocStart);
1350 const char *endBuf = SM->getCharacterData(LocEnd);
1351 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1352 }
1353 for (ObjCCategoryImplDecl::propimpl_iterator
1354 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1355 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1356 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001357 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001358 }
1359
1360 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1361}
1362
1363void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001364 // Do not synthesize more than once.
1365 if (ObjCSynthesizedStructs.count(ClassDecl))
1366 return;
1367 // Make sure super class's are written before current class is written.
1368 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1369 while (SuperClass) {
1370 RewriteInterfaceDecl(SuperClass);
1371 SuperClass = SuperClass->getSuperClass();
1372 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001373 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001374 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001375 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001376 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001377 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1378
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001379 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001380 // Mark this typedef as having been written into its c++ equivalent.
1381 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001382
1383 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001384 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001385 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001386 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001387 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001388 I != E; ++I)
1389 RewriteMethodDeclaration(*I);
1390 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001391 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001392 I != E; ++I)
1393 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001394
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001395 // Lastly, comment out the @end.
1396 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1397 "/* @end */");
1398 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001399}
1400
1401Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1402 SourceRange OldRange = PseudoOp->getSourceRange();
1403
1404 // We just magically know some things about the structure of this
1405 // expression.
1406 ObjCMessageExpr *OldMsg =
1407 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1408 PseudoOp->getNumSemanticExprs() - 1));
1409
1410 // Because the rewriter doesn't allow us to rewrite rewritten code,
1411 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001412 Expr *Base;
1413 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001414 {
1415 DisableReplaceStmtScope S(*this);
1416
1417 // Rebuild the base expression if we have one.
1418 Base = 0;
1419 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1420 Base = OldMsg->getInstanceReceiver();
1421 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1422 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1423 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001424
1425 unsigned numArgs = OldMsg->getNumArgs();
1426 for (unsigned i = 0; i < numArgs; i++) {
1427 Expr *Arg = OldMsg->getArg(i);
1428 if (isa<OpaqueValueExpr>(Arg))
1429 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1430 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1431 Args.push_back(Arg);
1432 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001433 }
1434
1435 // TODO: avoid this copy.
1436 SmallVector<SourceLocation, 1> SelLocs;
1437 OldMsg->getSelectorLocs(SelLocs);
1438
1439 ObjCMessageExpr *NewMsg = 0;
1440 switch (OldMsg->getReceiverKind()) {
1441 case ObjCMessageExpr::Class:
1442 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1443 OldMsg->getValueKind(),
1444 OldMsg->getLeftLoc(),
1445 OldMsg->getClassReceiverTypeInfo(),
1446 OldMsg->getSelector(),
1447 SelLocs,
1448 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001449 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001450 OldMsg->getRightLoc(),
1451 OldMsg->isImplicit());
1452 break;
1453
1454 case ObjCMessageExpr::Instance:
1455 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1456 OldMsg->getValueKind(),
1457 OldMsg->getLeftLoc(),
1458 Base,
1459 OldMsg->getSelector(),
1460 SelLocs,
1461 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001462 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001463 OldMsg->getRightLoc(),
1464 OldMsg->isImplicit());
1465 break;
1466
1467 case ObjCMessageExpr::SuperClass:
1468 case ObjCMessageExpr::SuperInstance:
1469 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1470 OldMsg->getValueKind(),
1471 OldMsg->getLeftLoc(),
1472 OldMsg->getSuperLoc(),
1473 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1474 OldMsg->getSuperType(),
1475 OldMsg->getSelector(),
1476 SelLocs,
1477 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001478 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001479 OldMsg->getRightLoc(),
1480 OldMsg->isImplicit());
1481 break;
1482 }
1483
1484 Stmt *Replacement = SynthMessageExpr(NewMsg);
1485 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1486 return Replacement;
1487}
1488
1489Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1490 SourceRange OldRange = PseudoOp->getSourceRange();
1491
1492 // We just magically know some things about the structure of this
1493 // expression.
1494 ObjCMessageExpr *OldMsg =
1495 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1496
1497 // Because the rewriter doesn't allow us to rewrite rewritten code,
1498 // we need to suppress rewriting the sub-statements.
1499 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001500 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001501 {
1502 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001503 // Rebuild the base expression if we have one.
1504 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1505 Base = OldMsg->getInstanceReceiver();
1506 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1507 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1508 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001509 unsigned numArgs = OldMsg->getNumArgs();
1510 for (unsigned i = 0; i < numArgs; i++) {
1511 Expr *Arg = OldMsg->getArg(i);
1512 if (isa<OpaqueValueExpr>(Arg))
1513 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1514 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1515 Args.push_back(Arg);
1516 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001517 }
1518
1519 // Intentionally empty.
1520 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001521
1522 ObjCMessageExpr *NewMsg = 0;
1523 switch (OldMsg->getReceiverKind()) {
1524 case ObjCMessageExpr::Class:
1525 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1526 OldMsg->getValueKind(),
1527 OldMsg->getLeftLoc(),
1528 OldMsg->getClassReceiverTypeInfo(),
1529 OldMsg->getSelector(),
1530 SelLocs,
1531 OldMsg->getMethodDecl(),
1532 Args,
1533 OldMsg->getRightLoc(),
1534 OldMsg->isImplicit());
1535 break;
1536
1537 case ObjCMessageExpr::Instance:
1538 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1539 OldMsg->getValueKind(),
1540 OldMsg->getLeftLoc(),
1541 Base,
1542 OldMsg->getSelector(),
1543 SelLocs,
1544 OldMsg->getMethodDecl(),
1545 Args,
1546 OldMsg->getRightLoc(),
1547 OldMsg->isImplicit());
1548 break;
1549
1550 case ObjCMessageExpr::SuperClass:
1551 case ObjCMessageExpr::SuperInstance:
1552 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1553 OldMsg->getValueKind(),
1554 OldMsg->getLeftLoc(),
1555 OldMsg->getSuperLoc(),
1556 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1557 OldMsg->getSuperType(),
1558 OldMsg->getSelector(),
1559 SelLocs,
1560 OldMsg->getMethodDecl(),
1561 Args,
1562 OldMsg->getRightLoc(),
1563 OldMsg->isImplicit());
1564 break;
1565 }
1566
1567 Stmt *Replacement = SynthMessageExpr(NewMsg);
1568 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1569 return Replacement;
1570}
1571
1572/// SynthCountByEnumWithState - To print:
1573/// ((unsigned int (*)
1574/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1575/// (void *)objc_msgSend)((id)l_collection,
1576/// sel_registerName(
1577/// "countByEnumeratingWithState:objects:count:"),
1578/// &enumState,
1579/// (id *)__rw_items, (unsigned int)16)
1580///
1581void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1582 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1583 "id *, unsigned int))(void *)objc_msgSend)";
1584 buf += "\n\t\t";
1585 buf += "((id)l_collection,\n\t\t";
1586 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1587 buf += "\n\t\t";
1588 buf += "&enumState, "
1589 "(id *)__rw_items, (unsigned int)16)";
1590}
1591
1592/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1593/// statement to exit to its outer synthesized loop.
1594///
1595Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1596 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1597 return S;
1598 // replace break with goto __break_label
1599 std::string buf;
1600
1601 SourceLocation startLoc = S->getLocStart();
1602 buf = "goto __break_label_";
1603 buf += utostr(ObjCBcLabelNo.back());
1604 ReplaceText(startLoc, strlen("break"), buf);
1605
1606 return 0;
1607}
1608
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001609void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1610 SourceLocation Loc,
1611 std::string &LineString) {
1612 if (Loc.isFileID()) {
1613 LineString += "\n#line ";
1614 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1615 LineString += utostr(PLoc.getLine());
1616 LineString += " \"";
1617 LineString += Lexer::Stringify(PLoc.getFilename());
1618 LineString += "\"\n";
1619 }
1620}
1621
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001622/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1623/// statement to continue with its inner synthesized loop.
1624///
1625Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1626 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1627 return S;
1628 // replace continue with goto __continue_label
1629 std::string buf;
1630
1631 SourceLocation startLoc = S->getLocStart();
1632 buf = "goto __continue_label_";
1633 buf += utostr(ObjCBcLabelNo.back());
1634 ReplaceText(startLoc, strlen("continue"), buf);
1635
1636 return 0;
1637}
1638
1639/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1640/// It rewrites:
1641/// for ( type elem in collection) { stmts; }
1642
1643/// Into:
1644/// {
1645/// type elem;
1646/// struct __objcFastEnumerationState enumState = { 0 };
1647/// id __rw_items[16];
1648/// id l_collection = (id)collection;
1649/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1650/// objects:__rw_items count:16];
1651/// if (limit) {
1652/// unsigned long startMutations = *enumState.mutationsPtr;
1653/// do {
1654/// unsigned long counter = 0;
1655/// do {
1656/// if (startMutations != *enumState.mutationsPtr)
1657/// objc_enumerationMutation(l_collection);
1658/// elem = (type)enumState.itemsPtr[counter++];
1659/// stmts;
1660/// __continue_label: ;
1661/// } while (counter < limit);
1662/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1663/// objects:__rw_items count:16]);
1664/// elem = nil;
1665/// __break_label: ;
1666/// }
1667/// else
1668/// elem = nil;
1669/// }
1670///
1671Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1672 SourceLocation OrigEnd) {
1673 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1674 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1675 "ObjCForCollectionStmt Statement stack mismatch");
1676 assert(!ObjCBcLabelNo.empty() &&
1677 "ObjCForCollectionStmt - Label No stack empty");
1678
1679 SourceLocation startLoc = S->getLocStart();
1680 const char *startBuf = SM->getCharacterData(startLoc);
1681 StringRef elementName;
1682 std::string elementTypeAsString;
1683 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001684 // line directive first.
1685 SourceLocation ForEachLoc = S->getForLoc();
1686 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1687 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001688 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1689 // type elem;
1690 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1691 QualType ElementType = cast<ValueDecl>(D)->getType();
1692 if (ElementType->isObjCQualifiedIdType() ||
1693 ElementType->isObjCQualifiedInterfaceType())
1694 // Simply use 'id' for all qualified types.
1695 elementTypeAsString = "id";
1696 else
1697 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1698 buf += elementTypeAsString;
1699 buf += " ";
1700 elementName = D->getName();
1701 buf += elementName;
1702 buf += ";\n\t";
1703 }
1704 else {
1705 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1706 elementName = DR->getDecl()->getName();
1707 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1708 if (VD->getType()->isObjCQualifiedIdType() ||
1709 VD->getType()->isObjCQualifiedInterfaceType())
1710 // Simply use 'id' for all qualified types.
1711 elementTypeAsString = "id";
1712 else
1713 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1714 }
1715
1716 // struct __objcFastEnumerationState enumState = { 0 };
1717 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1718 // id __rw_items[16];
1719 buf += "id __rw_items[16];\n\t";
1720 // id l_collection = (id)
1721 buf += "id l_collection = (id)";
1722 // Find start location of 'collection' the hard way!
1723 const char *startCollectionBuf = startBuf;
1724 startCollectionBuf += 3; // skip 'for'
1725 startCollectionBuf = strchr(startCollectionBuf, '(');
1726 startCollectionBuf++; // skip '('
1727 // find 'in' and skip it.
1728 while (*startCollectionBuf != ' ' ||
1729 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1730 (*(startCollectionBuf+3) != ' ' &&
1731 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1732 startCollectionBuf++;
1733 startCollectionBuf += 3;
1734
1735 // Replace: "for (type element in" with string constructed thus far.
1736 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1737 // Replace ')' in for '(' type elem in collection ')' with ';'
1738 SourceLocation rightParenLoc = S->getRParenLoc();
1739 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1740 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1741 buf = ";\n\t";
1742
1743 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1744 // objects:__rw_items count:16];
1745 // which is synthesized into:
1746 // unsigned int limit =
1747 // ((unsigned int (*)
1748 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1749 // (void *)objc_msgSend)((id)l_collection,
1750 // sel_registerName(
1751 // "countByEnumeratingWithState:objects:count:"),
1752 // (struct __objcFastEnumerationState *)&state,
1753 // (id *)__rw_items, (unsigned int)16);
1754 buf += "unsigned long limit =\n\t\t";
1755 SynthCountByEnumWithState(buf);
1756 buf += ";\n\t";
1757 /// if (limit) {
1758 /// unsigned long startMutations = *enumState.mutationsPtr;
1759 /// do {
1760 /// unsigned long counter = 0;
1761 /// do {
1762 /// if (startMutations != *enumState.mutationsPtr)
1763 /// objc_enumerationMutation(l_collection);
1764 /// elem = (type)enumState.itemsPtr[counter++];
1765 buf += "if (limit) {\n\t";
1766 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1767 buf += "do {\n\t\t";
1768 buf += "unsigned long counter = 0;\n\t\t";
1769 buf += "do {\n\t\t\t";
1770 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1771 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1772 buf += elementName;
1773 buf += " = (";
1774 buf += elementTypeAsString;
1775 buf += ")enumState.itemsPtr[counter++];";
1776 // Replace ')' in for '(' type elem in collection ')' with all of these.
1777 ReplaceText(lparenLoc, 1, buf);
1778
1779 /// __continue_label: ;
1780 /// } while (counter < limit);
1781 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1782 /// objects:__rw_items count:16]);
1783 /// elem = nil;
1784 /// __break_label: ;
1785 /// }
1786 /// else
1787 /// elem = nil;
1788 /// }
1789 ///
1790 buf = ";\n\t";
1791 buf += "__continue_label_";
1792 buf += utostr(ObjCBcLabelNo.back());
1793 buf += ": ;";
1794 buf += "\n\t\t";
1795 buf += "} while (counter < limit);\n\t";
1796 buf += "} while (limit = ";
1797 SynthCountByEnumWithState(buf);
1798 buf += ");\n\t";
1799 buf += elementName;
1800 buf += " = ((";
1801 buf += elementTypeAsString;
1802 buf += ")0);\n\t";
1803 buf += "__break_label_";
1804 buf += utostr(ObjCBcLabelNo.back());
1805 buf += ": ;\n\t";
1806 buf += "}\n\t";
1807 buf += "else\n\t\t";
1808 buf += elementName;
1809 buf += " = ((";
1810 buf += elementTypeAsString;
1811 buf += ")0);\n\t";
1812 buf += "}\n";
1813
1814 // Insert all these *after* the statement body.
1815 // FIXME: If this should support Obj-C++, support CXXTryStmt
1816 if (isa<CompoundStmt>(S->getBody())) {
1817 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1818 InsertText(endBodyLoc, buf);
1819 } else {
1820 /* Need to treat single statements specially. For example:
1821 *
1822 * for (A *a in b) if (stuff()) break;
1823 * for (A *a in b) xxxyy;
1824 *
1825 * The following code simply scans ahead to the semi to find the actual end.
1826 */
1827 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1828 const char *semiBuf = strchr(stmtBuf, ';');
1829 assert(semiBuf && "Can't find ';'");
1830 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1831 InsertText(endBodyLoc, buf);
1832 }
1833 Stmts.pop_back();
1834 ObjCBcLabelNo.pop_back();
1835 return 0;
1836}
1837
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001838static void Write_RethrowObject(std::string &buf) {
1839 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1840 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1841 buf += "\tid rethrow;\n";
1842 buf += "\t} _fin_force_rethow(_rethrow);";
1843}
1844
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001845/// RewriteObjCSynchronizedStmt -
1846/// This routine rewrites @synchronized(expr) stmt;
1847/// into:
1848/// objc_sync_enter(expr);
1849/// @try stmt @finally { objc_sync_exit(expr); }
1850///
1851Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1852 // Get the start location and compute the semi location.
1853 SourceLocation startLoc = S->getLocStart();
1854 const char *startBuf = SM->getCharacterData(startLoc);
1855
1856 assert((*startBuf == '@') && "bogus @synchronized location");
1857
1858 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001859 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1860 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1861 buf += "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001862
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001863 const char *lparenBuf = startBuf;
1864 while (*lparenBuf != '(') lparenBuf++;
1865 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001866
1867 buf = "; objc_sync_enter(_sync_obj);\n";
1868 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1869 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1870 buf += "\n\tid sync_exit;";
1871 buf += "\n\t} _sync_exit(_sync_obj);\n";
1872
1873 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1874 // the sync expression is typically a message expression that's already
1875 // been rewritten! (which implies the SourceLocation's are invalid).
1876 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1877 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1878 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1879 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1880
1881 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1882 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1883 assert (*LBraceLocBuf == '{');
1884 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001885
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001886 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001887 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1888 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001889
1890 buf = "} catch (id e) {_rethrow = e;}\n";
1891 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001892 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001893 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001894
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001895 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001896
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001897 return 0;
1898}
1899
1900void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1901{
1902 // Perform a bottom up traversal of all children.
1903 for (Stmt::child_range CI = S->children(); CI; ++CI)
1904 if (*CI)
1905 WarnAboutReturnGotoStmts(*CI);
1906
1907 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1908 Diags.Report(Context->getFullLoc(S->getLocStart()),
1909 TryFinallyContainsReturnDiag);
1910 }
1911 return;
1912}
1913
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001914Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1915 SourceLocation startLoc = S->getAtLoc();
1916 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001917 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1918 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001919
1920 return 0;
1921}
1922
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001923Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001924 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001925 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001926 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001927 SourceLocation TryLocation = S->getAtTryLoc();
1928 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001929
1930 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001931 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001932 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001933 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001934 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001935 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001936 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001937 // Get the start location and compute the semi location.
1938 SourceLocation startLoc = S->getLocStart();
1939 const char *startBuf = SM->getCharacterData(startLoc);
1940
1941 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001942 if (finalStmt)
1943 ReplaceText(startLoc, 1, buf);
1944 else
1945 // @try -> try
1946 ReplaceText(startLoc, 1, "");
1947
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001948 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1949 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001950 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001951
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001952 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001953 bool AtRemoved = false;
1954 if (catchDecl) {
1955 QualType t = catchDecl->getType();
1956 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1957 // Should be a pointer to a class.
1958 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1959 if (IDecl) {
1960 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001961 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1962
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001963 startBuf = SM->getCharacterData(startLoc);
1964 assert((*startBuf == '@') && "bogus @catch location");
1965 SourceLocation rParenLoc = Catch->getRParenLoc();
1966 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1967
1968 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001969 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001970 Result += " *_"; Result += catchDecl->getNameAsString();
1971 Result += ")";
1972 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1973 // Foo *e = (Foo *)_e;
1974 Result.clear();
1975 Result = "{ ";
1976 Result += IDecl->getNameAsString();
1977 Result += " *"; Result += catchDecl->getNameAsString();
1978 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1979 Result += "_"; Result += catchDecl->getNameAsString();
1980
1981 Result += "; ";
1982 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1983 ReplaceText(lBraceLoc, 1, Result);
1984 AtRemoved = true;
1985 }
1986 }
1987 }
1988 if (!AtRemoved)
1989 // @catch -> catch
1990 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001991
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001992 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001993 if (finalStmt) {
1994 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001995 SourceLocation FinallyLoc = finalStmt->getLocStart();
1996
1997 if (noCatch) {
1998 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
1999 buf += "catch (id e) {_rethrow = e;}\n";
2000 }
2001 else {
2002 buf += "}\n";
2003 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2004 buf += "catch (id e) {_rethrow = e;}\n";
2005 }
2006
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002007 SourceLocation startFinalLoc = finalStmt->getLocStart();
2008 ReplaceText(startFinalLoc, 8, buf);
2009 Stmt *body = finalStmt->getFinallyBody();
2010 SourceLocation startFinalBodyLoc = body->getLocStart();
2011 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002012 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002013 ReplaceText(startFinalBodyLoc, 1, buf);
2014
2015 SourceLocation endFinalBodyLoc = body->getLocEnd();
2016 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002017 // Now check for any return/continue/go statements within the @try.
2018 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002019 }
2020
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002021 return 0;
2022}
2023
2024// This can't be done with ReplaceStmt(S, ThrowExpr), since
2025// the throw expression is typically a message expression that's already
2026// been rewritten! (which implies the SourceLocation's are invalid).
2027Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2028 // Get the start location and compute the semi location.
2029 SourceLocation startLoc = S->getLocStart();
2030 const char *startBuf = SM->getCharacterData(startLoc);
2031
2032 assert((*startBuf == '@') && "bogus @throw location");
2033
2034 std::string buf;
2035 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2036 if (S->getThrowExpr())
2037 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002038 else
2039 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002040
2041 // handle "@ throw" correctly.
2042 const char *wBuf = strchr(startBuf, 'w');
2043 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2044 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2045
2046 const char *semiBuf = strchr(startBuf, ';');
2047 assert((*semiBuf == ';') && "@throw: can't find ';'");
2048 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002049 if (S->getThrowExpr())
2050 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002051 return 0;
2052}
2053
2054Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2055 // Create a new string expression.
2056 QualType StrType = Context->getPointerType(Context->CharTy);
2057 std::string StrEncoding;
2058 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2059 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2060 StringLiteral::Ascii, false,
2061 StrType, SourceLocation());
2062 ReplaceStmt(Exp, Replacement);
2063
2064 // Replace this subexpr in the parent.
2065 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2066 return Replacement;
2067}
2068
2069Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2070 if (!SelGetUidFunctionDecl)
2071 SynthSelGetUidFunctionDecl();
2072 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2073 // Create a call to sel_registerName("selName").
2074 SmallVector<Expr*, 8> SelExprs;
2075 QualType argType = Context->getPointerType(Context->CharTy);
2076 SelExprs.push_back(StringLiteral::Create(*Context,
2077 Exp->getSelector().getAsString(),
2078 StringLiteral::Ascii, false,
2079 argType, SourceLocation()));
2080 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2081 &SelExprs[0], SelExprs.size());
2082 ReplaceStmt(Exp, SelExp);
2083 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2084 return SelExp;
2085}
2086
2087CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2088 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2089 SourceLocation EndLoc) {
2090 // Get the type, we will need to reference it in a couple spots.
2091 QualType msgSendType = FD->getType();
2092
2093 // Create a reference to the objc_msgSend() declaration.
2094 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002095 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002096
2097 // Now, we cast the reference to a pointer to the objc_msgSend type.
2098 QualType pToFunc = Context->getPointerType(msgSendType);
2099 ImplicitCastExpr *ICE =
2100 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2101 DRE, 0, VK_RValue);
2102
2103 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2104
2105 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002106 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002107 FT->getCallResultType(*Context),
2108 VK_RValue, EndLoc);
2109 return Exp;
2110}
2111
2112static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2113 const char *&startRef, const char *&endRef) {
2114 while (startBuf < endBuf) {
2115 if (*startBuf == '<')
2116 startRef = startBuf; // mark the start.
2117 if (*startBuf == '>') {
2118 if (startRef && *startRef == '<') {
2119 endRef = startBuf; // mark the end.
2120 return true;
2121 }
2122 return false;
2123 }
2124 startBuf++;
2125 }
2126 return false;
2127}
2128
2129static void scanToNextArgument(const char *&argRef) {
2130 int angle = 0;
2131 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2132 if (*argRef == '<')
2133 angle++;
2134 else if (*argRef == '>')
2135 angle--;
2136 argRef++;
2137 }
2138 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2139}
2140
2141bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2142 if (T->isObjCQualifiedIdType())
2143 return true;
2144 if (const PointerType *PT = T->getAs<PointerType>()) {
2145 if (PT->getPointeeType()->isObjCQualifiedIdType())
2146 return true;
2147 }
2148 if (T->isObjCObjectPointerType()) {
2149 T = T->getPointeeType();
2150 return T->isObjCQualifiedInterfaceType();
2151 }
2152 if (T->isArrayType()) {
2153 QualType ElemTy = Context->getBaseElementType(T);
2154 return needToScanForQualifiers(ElemTy);
2155 }
2156 return false;
2157}
2158
2159void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2160 QualType Type = E->getType();
2161 if (needToScanForQualifiers(Type)) {
2162 SourceLocation Loc, EndLoc;
2163
2164 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2165 Loc = ECE->getLParenLoc();
2166 EndLoc = ECE->getRParenLoc();
2167 } else {
2168 Loc = E->getLocStart();
2169 EndLoc = E->getLocEnd();
2170 }
2171 // This will defend against trying to rewrite synthesized expressions.
2172 if (Loc.isInvalid() || EndLoc.isInvalid())
2173 return;
2174
2175 const char *startBuf = SM->getCharacterData(Loc);
2176 const char *endBuf = SM->getCharacterData(EndLoc);
2177 const char *startRef = 0, *endRef = 0;
2178 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2179 // Get the locations of the startRef, endRef.
2180 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2181 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2182 // Comment out the protocol references.
2183 InsertText(LessLoc, "/*");
2184 InsertText(GreaterLoc, "*/");
2185 }
2186 }
2187}
2188
2189void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2190 SourceLocation Loc;
2191 QualType Type;
2192 const FunctionProtoType *proto = 0;
2193 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2194 Loc = VD->getLocation();
2195 Type = VD->getType();
2196 }
2197 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2198 Loc = FD->getLocation();
2199 // Check for ObjC 'id' and class types that have been adorned with protocol
2200 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2201 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2202 assert(funcType && "missing function type");
2203 proto = dyn_cast<FunctionProtoType>(funcType);
2204 if (!proto)
2205 return;
2206 Type = proto->getResultType();
2207 }
2208 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2209 Loc = FD->getLocation();
2210 Type = FD->getType();
2211 }
2212 else
2213 return;
2214
2215 if (needToScanForQualifiers(Type)) {
2216 // Since types are unique, we need to scan the buffer.
2217
2218 const char *endBuf = SM->getCharacterData(Loc);
2219 const char *startBuf = endBuf;
2220 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2221 startBuf--; // scan backward (from the decl location) for return type.
2222 const char *startRef = 0, *endRef = 0;
2223 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2224 // Get the locations of the startRef, endRef.
2225 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2226 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2227 // Comment out the protocol references.
2228 InsertText(LessLoc, "/*");
2229 InsertText(GreaterLoc, "*/");
2230 }
2231 }
2232 if (!proto)
2233 return; // most likely, was a variable
2234 // Now check arguments.
2235 const char *startBuf = SM->getCharacterData(Loc);
2236 const char *startFuncBuf = startBuf;
2237 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2238 if (needToScanForQualifiers(proto->getArgType(i))) {
2239 // Since types are unique, we need to scan the buffer.
2240
2241 const char *endBuf = startBuf;
2242 // scan forward (from the decl location) for argument types.
2243 scanToNextArgument(endBuf);
2244 const char *startRef = 0, *endRef = 0;
2245 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2246 // Get the locations of the startRef, endRef.
2247 SourceLocation LessLoc =
2248 Loc.getLocWithOffset(startRef-startFuncBuf);
2249 SourceLocation GreaterLoc =
2250 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2251 // Comment out the protocol references.
2252 InsertText(LessLoc, "/*");
2253 InsertText(GreaterLoc, "*/");
2254 }
2255 startBuf = ++endBuf;
2256 }
2257 else {
2258 // If the function name is derived from a macro expansion, then the
2259 // argument buffer will not follow the name. Need to speak with Chris.
2260 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2261 startBuf++; // scan forward (from the decl location) for argument types.
2262 startBuf++;
2263 }
2264 }
2265}
2266
2267void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2268 QualType QT = ND->getType();
2269 const Type* TypePtr = QT->getAs<Type>();
2270 if (!isa<TypeOfExprType>(TypePtr))
2271 return;
2272 while (isa<TypeOfExprType>(TypePtr)) {
2273 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2274 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2275 TypePtr = QT->getAs<Type>();
2276 }
2277 // FIXME. This will not work for multiple declarators; as in:
2278 // __typeof__(a) b,c,d;
2279 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2280 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2281 const char *startBuf = SM->getCharacterData(DeclLoc);
2282 if (ND->getInit()) {
2283 std::string Name(ND->getNameAsString());
2284 TypeAsString += " " + Name + " = ";
2285 Expr *E = ND->getInit();
2286 SourceLocation startLoc;
2287 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2288 startLoc = ECE->getLParenLoc();
2289 else
2290 startLoc = E->getLocStart();
2291 startLoc = SM->getExpansionLoc(startLoc);
2292 const char *endBuf = SM->getCharacterData(startLoc);
2293 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2294 }
2295 else {
2296 SourceLocation X = ND->getLocEnd();
2297 X = SM->getExpansionLoc(X);
2298 const char *endBuf = SM->getCharacterData(X);
2299 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2300 }
2301}
2302
2303// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2304void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2305 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2306 SmallVector<QualType, 16> ArgTys;
2307 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2308 QualType getFuncType =
2309 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2310 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2311 SourceLocation(),
2312 SourceLocation(),
2313 SelGetUidIdent, getFuncType, 0,
2314 SC_Extern,
2315 SC_None, false);
2316}
2317
2318void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2319 // declared in <objc/objc.h>
2320 if (FD->getIdentifier() &&
2321 FD->getName() == "sel_registerName") {
2322 SelGetUidFunctionDecl = FD;
2323 return;
2324 }
2325 RewriteObjCQualifiedInterfaceTypes(FD);
2326}
2327
2328void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2329 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2330 const char *argPtr = TypeString.c_str();
2331 if (!strchr(argPtr, '^')) {
2332 Str += TypeString;
2333 return;
2334 }
2335 while (*argPtr) {
2336 Str += (*argPtr == '^' ? '*' : *argPtr);
2337 argPtr++;
2338 }
2339}
2340
2341// FIXME. Consolidate this routine with RewriteBlockPointerType.
2342void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2343 ValueDecl *VD) {
2344 QualType Type = VD->getType();
2345 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2346 const char *argPtr = TypeString.c_str();
2347 int paren = 0;
2348 while (*argPtr) {
2349 switch (*argPtr) {
2350 case '(':
2351 Str += *argPtr;
2352 paren++;
2353 break;
2354 case ')':
2355 Str += *argPtr;
2356 paren--;
2357 break;
2358 case '^':
2359 Str += '*';
2360 if (paren == 1)
2361 Str += VD->getNameAsString();
2362 break;
2363 default:
2364 Str += *argPtr;
2365 break;
2366 }
2367 argPtr++;
2368 }
2369}
2370
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002371void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2372 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2373 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2374 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2375 if (!proto)
2376 return;
2377 QualType Type = proto->getResultType();
2378 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2379 FdStr += " ";
2380 FdStr += FD->getName();
2381 FdStr += "(";
2382 unsigned numArgs = proto->getNumArgs();
2383 for (unsigned i = 0; i < numArgs; i++) {
2384 QualType ArgType = proto->getArgType(i);
2385 RewriteBlockPointerType(FdStr, ArgType);
2386 if (i+1 < numArgs)
2387 FdStr += ", ";
2388 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002389 if (FD->isVariadic()) {
2390 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2391 }
2392 else
2393 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002394 InsertText(FunLocStart, FdStr);
2395}
2396
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002397// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002398void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2399 if (SuperContructorFunctionDecl)
2400 return;
2401 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2402 SmallVector<QualType, 16> ArgTys;
2403 QualType argT = Context->getObjCIdType();
2404 assert(!argT.isNull() && "Can't find 'id' type");
2405 ArgTys.push_back(argT);
2406 ArgTys.push_back(argT);
2407 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2408 &ArgTys[0], ArgTys.size());
2409 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2410 SourceLocation(),
2411 SourceLocation(),
2412 msgSendIdent, msgSendType, 0,
2413 SC_Extern,
2414 SC_None, false);
2415}
2416
2417// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2418void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2419 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2420 SmallVector<QualType, 16> ArgTys;
2421 QualType argT = Context->getObjCIdType();
2422 assert(!argT.isNull() && "Can't find 'id' type");
2423 ArgTys.push_back(argT);
2424 argT = Context->getObjCSelType();
2425 assert(!argT.isNull() && "Can't find 'SEL' type");
2426 ArgTys.push_back(argT);
2427 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2428 &ArgTys[0], ArgTys.size(),
2429 true /*isVariadic*/);
2430 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2431 SourceLocation(),
2432 SourceLocation(),
2433 msgSendIdent, msgSendType, 0,
2434 SC_Extern,
2435 SC_None, false);
2436}
2437
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002438// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002439void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2440 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002441 SmallVector<QualType, 2> ArgTys;
2442 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002443 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002444 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002445 true /*isVariadic*/);
2446 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2447 SourceLocation(),
2448 SourceLocation(),
2449 msgSendIdent, msgSendType, 0,
2450 SC_Extern,
2451 SC_None, false);
2452}
2453
2454// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2455void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2456 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2457 SmallVector<QualType, 16> ArgTys;
2458 QualType argT = Context->getObjCIdType();
2459 assert(!argT.isNull() && "Can't find 'id' type");
2460 ArgTys.push_back(argT);
2461 argT = Context->getObjCSelType();
2462 assert(!argT.isNull() && "Can't find 'SEL' type");
2463 ArgTys.push_back(argT);
2464 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2465 &ArgTys[0], ArgTys.size(),
2466 true /*isVariadic*/);
2467 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2468 SourceLocation(),
2469 SourceLocation(),
2470 msgSendIdent, msgSendType, 0,
2471 SC_Extern,
2472 SC_None, false);
2473}
2474
2475// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002476// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002477void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2478 IdentifierInfo *msgSendIdent =
2479 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002480 SmallVector<QualType, 2> ArgTys;
2481 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002482 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002483 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002484 true /*isVariadic*/);
2485 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2486 SourceLocation(),
2487 SourceLocation(),
2488 msgSendIdent, msgSendType, 0,
2489 SC_Extern,
2490 SC_None, false);
2491}
2492
2493// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2494void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2495 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2496 SmallVector<QualType, 16> ArgTys;
2497 QualType argT = Context->getObjCIdType();
2498 assert(!argT.isNull() && "Can't find 'id' type");
2499 ArgTys.push_back(argT);
2500 argT = Context->getObjCSelType();
2501 assert(!argT.isNull() && "Can't find 'SEL' type");
2502 ArgTys.push_back(argT);
2503 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2504 &ArgTys[0], ArgTys.size(),
2505 true /*isVariadic*/);
2506 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2507 SourceLocation(),
2508 SourceLocation(),
2509 msgSendIdent, msgSendType, 0,
2510 SC_Extern,
2511 SC_None, false);
2512}
2513
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002514// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002515void RewriteModernObjC::SynthGetClassFunctionDecl() {
2516 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2517 SmallVector<QualType, 16> ArgTys;
2518 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002519 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002520 &ArgTys[0], ArgTys.size());
2521 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2522 SourceLocation(),
2523 SourceLocation(),
2524 getClassIdent, getClassType, 0,
2525 SC_Extern,
2526 SC_None, false);
2527}
2528
2529// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2530void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2531 IdentifierInfo *getSuperClassIdent =
2532 &Context->Idents.get("class_getSuperclass");
2533 SmallVector<QualType, 16> ArgTys;
2534 ArgTys.push_back(Context->getObjCClassType());
2535 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2536 &ArgTys[0], ArgTys.size());
2537 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2538 SourceLocation(),
2539 SourceLocation(),
2540 getSuperClassIdent,
2541 getClassType, 0,
2542 SC_Extern,
2543 SC_None,
2544 false);
2545}
2546
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002547// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002548void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2549 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2550 SmallVector<QualType, 16> ArgTys;
2551 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002552 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002553 &ArgTys[0], ArgTys.size());
2554 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2555 SourceLocation(),
2556 SourceLocation(),
2557 getClassIdent, getClassType, 0,
2558 SC_Extern,
2559 SC_None, false);
2560}
2561
2562Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2563 QualType strType = getConstantStringStructType();
2564
2565 std::string S = "__NSConstantStringImpl_";
2566
2567 std::string tmpName = InFileName;
2568 unsigned i;
2569 for (i=0; i < tmpName.length(); i++) {
2570 char c = tmpName.at(i);
2571 // replace any non alphanumeric characters with '_'.
2572 if (!isalpha(c) && (c < '0' || c > '9'))
2573 tmpName[i] = '_';
2574 }
2575 S += tmpName;
2576 S += "_";
2577 S += utostr(NumObjCStringLiterals++);
2578
2579 Preamble += "static __NSConstantStringImpl " + S;
2580 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2581 Preamble += "0x000007c8,"; // utf8_str
2582 // The pretty printer for StringLiteral handles escape characters properly.
2583 std::string prettyBufS;
2584 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002585 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002586 Preamble += prettyBuf.str();
2587 Preamble += ",";
2588 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2589
2590 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2591 SourceLocation(), &Context->Idents.get(S),
2592 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002593 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002594 SourceLocation());
2595 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2596 Context->getPointerType(DRE->getType()),
2597 VK_RValue, OK_Ordinary,
2598 SourceLocation());
2599 // cast to NSConstantString *
2600 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2601 CK_CPointerToObjCPointerCast, Unop);
2602 ReplaceStmt(Exp, cast);
2603 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2604 return cast;
2605}
2606
Fariborz Jahanian55947042012-03-27 20:17:30 +00002607Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2608 unsigned IntSize =
2609 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2610
2611 Expr *FlagExp = IntegerLiteral::Create(*Context,
2612 llvm::APInt(IntSize, Exp->getValue()),
2613 Context->IntTy, Exp->getLocation());
2614 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2615 CK_BitCast, FlagExp);
2616 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2617 cast);
2618 ReplaceStmt(Exp, PE);
2619 return PE;
2620}
2621
Patrick Beardeb382ec2012-04-19 00:25:12 +00002622Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002623 // synthesize declaration of helper functions needed in this routine.
2624 if (!SelGetUidFunctionDecl)
2625 SynthSelGetUidFunctionDecl();
2626 // use objc_msgSend() for all.
2627 if (!MsgSendFunctionDecl)
2628 SynthMsgSendFunctionDecl();
2629 if (!GetClassFunctionDecl)
2630 SynthGetClassFunctionDecl();
2631
2632 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2633 SourceLocation StartLoc = Exp->getLocStart();
2634 SourceLocation EndLoc = Exp->getLocEnd();
2635
2636 // Synthesize a call to objc_msgSend().
2637 SmallVector<Expr*, 4> MsgExprs;
2638 SmallVector<Expr*, 4> ClsExprs;
2639 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002640
Patrick Beardeb382ec2012-04-19 00:25:12 +00002641 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2642 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2643 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002644
Patrick Beardeb382ec2012-04-19 00:25:12 +00002645 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002646 ClsExprs.push_back(StringLiteral::Create(*Context,
2647 clsName->getName(),
2648 StringLiteral::Ascii, false,
2649 argType, SourceLocation()));
2650 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2651 &ClsExprs[0],
2652 ClsExprs.size(),
2653 StartLoc, EndLoc);
2654 MsgExprs.push_back(Cls);
2655
Patrick Beardeb382ec2012-04-19 00:25:12 +00002656 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002657 // it will be the 2nd argument.
2658 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002659 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002660 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002661 StringLiteral::Ascii, false,
2662 argType, SourceLocation()));
2663 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2664 &SelExprs[0], SelExprs.size(),
2665 StartLoc, EndLoc);
2666 MsgExprs.push_back(SelExp);
2667
Patrick Beardeb382ec2012-04-19 00:25:12 +00002668 // User provided sub-expression is the 3rd, and last, argument.
2669 Expr *subExpr = Exp->getSubExpr();
2670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002671 QualType type = ICE->getType();
2672 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2673 CastKind CK = CK_BitCast;
2674 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2675 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002676 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002677 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002678 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002679
2680 SmallVector<QualType, 4> ArgTypes;
2681 ArgTypes.push_back(Context->getObjCIdType());
2682 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002683 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2684 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002685 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002686
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002687 QualType returnType = Exp->getType();
2688 // Get the type, we will need to reference it in a couple spots.
2689 QualType msgSendType = MsgSendFlavor->getType();
2690
2691 // Create a reference to the objc_msgSend() declaration.
2692 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2693 VK_LValue, SourceLocation());
2694
2695 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002696 Context->getPointerType(Context->VoidTy),
2697 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002698
2699 // Now do the "normal" pointer to function cast.
2700 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002701 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2702 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002703 castType = Context->getPointerType(castType);
2704 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2705 cast);
2706
2707 // Don't forget the parens to enforce the proper binding.
2708 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2709
2710 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002711 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002712 FT->getResultType(), VK_RValue,
2713 EndLoc);
2714 ReplaceStmt(Exp, CE);
2715 return CE;
2716}
2717
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002718Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2719 // synthesize declaration of helper functions needed in this routine.
2720 if (!SelGetUidFunctionDecl)
2721 SynthSelGetUidFunctionDecl();
2722 // use objc_msgSend() for all.
2723 if (!MsgSendFunctionDecl)
2724 SynthMsgSendFunctionDecl();
2725 if (!GetClassFunctionDecl)
2726 SynthGetClassFunctionDecl();
2727
2728 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2729 SourceLocation StartLoc = Exp->getLocStart();
2730 SourceLocation EndLoc = Exp->getLocEnd();
2731
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002732 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002733 QualType IntQT = Context->IntTy;
2734 QualType NSArrayFType =
2735 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002736 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002737 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2738 DeclRefExpr *NSArrayDRE =
2739 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2740 SourceLocation());
2741
2742 SmallVector<Expr*, 16> InitExprs;
2743 unsigned NumElements = Exp->getNumElements();
2744 unsigned UnsignedIntSize =
2745 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2746 Expr *count = IntegerLiteral::Create(*Context,
2747 llvm::APInt(UnsignedIntSize, NumElements),
2748 Context->UnsignedIntTy, SourceLocation());
2749 InitExprs.push_back(count);
2750 for (unsigned i = 0; i < NumElements; i++)
2751 InitExprs.push_back(Exp->getElement(i));
2752 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002753 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002754 NSArrayFType, VK_LValue, SourceLocation());
2755
2756 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2757 SourceLocation(),
2758 &Context->Idents.get("arr"),
2759 Context->getPointerType(Context->VoidPtrTy), 0,
2760 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002761 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002762 MemberExpr *ArrayLiteralME =
2763 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2764 SourceLocation(),
2765 ARRFD->getType(), VK_LValue,
2766 OK_Ordinary);
2767 QualType ConstIdT = Context->getObjCIdType().withConst();
2768 CStyleCastExpr * ArrayLiteralObjects =
2769 NoTypeInfoCStyleCastExpr(Context,
2770 Context->getPointerType(ConstIdT),
2771 CK_BitCast,
2772 ArrayLiteralME);
2773
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002774 // Synthesize a call to objc_msgSend().
2775 SmallVector<Expr*, 32> MsgExprs;
2776 SmallVector<Expr*, 4> ClsExprs;
2777 QualType argType = Context->getPointerType(Context->CharTy);
2778 QualType expType = Exp->getType();
2779
2780 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2781 ObjCInterfaceDecl *Class =
2782 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2783
2784 IdentifierInfo *clsName = Class->getIdentifier();
2785 ClsExprs.push_back(StringLiteral::Create(*Context,
2786 clsName->getName(),
2787 StringLiteral::Ascii, false,
2788 argType, SourceLocation()));
2789 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2790 &ClsExprs[0],
2791 ClsExprs.size(),
2792 StartLoc, EndLoc);
2793 MsgExprs.push_back(Cls);
2794
2795 // Create a call to sel_registerName("arrayWithObjects:count:").
2796 // it will be the 2nd argument.
2797 SmallVector<Expr*, 4> SelExprs;
2798 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2799 SelExprs.push_back(StringLiteral::Create(*Context,
2800 ArrayMethod->getSelector().getAsString(),
2801 StringLiteral::Ascii, false,
2802 argType, SourceLocation()));
2803 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2804 &SelExprs[0], SelExprs.size(),
2805 StartLoc, EndLoc);
2806 MsgExprs.push_back(SelExp);
2807
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002808 // (const id [])objects
2809 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002810
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002811 // (NSUInteger)cnt
2812 Expr *cnt = IntegerLiteral::Create(*Context,
2813 llvm::APInt(UnsignedIntSize, NumElements),
2814 Context->UnsignedIntTy, SourceLocation());
2815 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002816
2817
2818 SmallVector<QualType, 4> ArgTypes;
2819 ArgTypes.push_back(Context->getObjCIdType());
2820 ArgTypes.push_back(Context->getObjCSelType());
2821 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2822 E = ArrayMethod->param_end(); PI != E; ++PI)
2823 ArgTypes.push_back((*PI)->getType());
2824
2825 QualType returnType = Exp->getType();
2826 // Get the type, we will need to reference it in a couple spots.
2827 QualType msgSendType = MsgSendFlavor->getType();
2828
2829 // Create a reference to the objc_msgSend() declaration.
2830 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2831 VK_LValue, SourceLocation());
2832
2833 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2834 Context->getPointerType(Context->VoidTy),
2835 CK_BitCast, DRE);
2836
2837 // Now do the "normal" pointer to function cast.
2838 QualType castType =
2839 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2840 ArrayMethod->isVariadic());
2841 castType = Context->getPointerType(castType);
2842 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2843 cast);
2844
2845 // Don't forget the parens to enforce the proper binding.
2846 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2847
2848 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002849 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002850 FT->getResultType(), VK_RValue,
2851 EndLoc);
2852 ReplaceStmt(Exp, CE);
2853 return CE;
2854}
2855
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002856Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2857 // synthesize declaration of helper functions needed in this routine.
2858 if (!SelGetUidFunctionDecl)
2859 SynthSelGetUidFunctionDecl();
2860 // use objc_msgSend() for all.
2861 if (!MsgSendFunctionDecl)
2862 SynthMsgSendFunctionDecl();
2863 if (!GetClassFunctionDecl)
2864 SynthGetClassFunctionDecl();
2865
2866 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2867 SourceLocation StartLoc = Exp->getLocStart();
2868 SourceLocation EndLoc = Exp->getLocEnd();
2869
2870 // Build the expression: __NSContainer_literal(int, ...).arr
2871 QualType IntQT = Context->IntTy;
2872 QualType NSDictFType =
2873 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2874 std::string NSDictFName("__NSContainer_literal");
2875 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2876 DeclRefExpr *NSDictDRE =
2877 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2878 SourceLocation());
2879
2880 SmallVector<Expr*, 16> KeyExprs;
2881 SmallVector<Expr*, 16> ValueExprs;
2882
2883 unsigned NumElements = Exp->getNumElements();
2884 unsigned UnsignedIntSize =
2885 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2886 Expr *count = IntegerLiteral::Create(*Context,
2887 llvm::APInt(UnsignedIntSize, NumElements),
2888 Context->UnsignedIntTy, SourceLocation());
2889 KeyExprs.push_back(count);
2890 ValueExprs.push_back(count);
2891 for (unsigned i = 0; i < NumElements; i++) {
2892 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2893 KeyExprs.push_back(Element.Key);
2894 ValueExprs.push_back(Element.Value);
2895 }
2896
2897 // (const id [])objects
2898 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002899 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002900 NSDictFType, VK_LValue, SourceLocation());
2901
2902 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2903 SourceLocation(),
2904 &Context->Idents.get("arr"),
2905 Context->getPointerType(Context->VoidPtrTy), 0,
2906 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002907 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002908 MemberExpr *DictLiteralValueME =
2909 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2910 SourceLocation(),
2911 ARRFD->getType(), VK_LValue,
2912 OK_Ordinary);
2913 QualType ConstIdT = Context->getObjCIdType().withConst();
2914 CStyleCastExpr * DictValueObjects =
2915 NoTypeInfoCStyleCastExpr(Context,
2916 Context->getPointerType(ConstIdT),
2917 CK_BitCast,
2918 DictLiteralValueME);
2919 // (const id <NSCopying> [])keys
2920 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002921 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002922 NSDictFType, VK_LValue, SourceLocation());
2923
2924 MemberExpr *DictLiteralKeyME =
2925 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2926 SourceLocation(),
2927 ARRFD->getType(), VK_LValue,
2928 OK_Ordinary);
2929
2930 CStyleCastExpr * DictKeyObjects =
2931 NoTypeInfoCStyleCastExpr(Context,
2932 Context->getPointerType(ConstIdT),
2933 CK_BitCast,
2934 DictLiteralKeyME);
2935
2936
2937
2938 // Synthesize a call to objc_msgSend().
2939 SmallVector<Expr*, 32> MsgExprs;
2940 SmallVector<Expr*, 4> ClsExprs;
2941 QualType argType = Context->getPointerType(Context->CharTy);
2942 QualType expType = Exp->getType();
2943
2944 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2945 ObjCInterfaceDecl *Class =
2946 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2947
2948 IdentifierInfo *clsName = Class->getIdentifier();
2949 ClsExprs.push_back(StringLiteral::Create(*Context,
2950 clsName->getName(),
2951 StringLiteral::Ascii, false,
2952 argType, SourceLocation()));
2953 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2954 &ClsExprs[0],
2955 ClsExprs.size(),
2956 StartLoc, EndLoc);
2957 MsgExprs.push_back(Cls);
2958
2959 // Create a call to sel_registerName("arrayWithObjects:count:").
2960 // it will be the 2nd argument.
2961 SmallVector<Expr*, 4> SelExprs;
2962 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2963 SelExprs.push_back(StringLiteral::Create(*Context,
2964 DictMethod->getSelector().getAsString(),
2965 StringLiteral::Ascii, false,
2966 argType, SourceLocation()));
2967 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2968 &SelExprs[0], SelExprs.size(),
2969 StartLoc, EndLoc);
2970 MsgExprs.push_back(SelExp);
2971
2972 // (const id [])objects
2973 MsgExprs.push_back(DictValueObjects);
2974
2975 // (const id <NSCopying> [])keys
2976 MsgExprs.push_back(DictKeyObjects);
2977
2978 // (NSUInteger)cnt
2979 Expr *cnt = IntegerLiteral::Create(*Context,
2980 llvm::APInt(UnsignedIntSize, NumElements),
2981 Context->UnsignedIntTy, SourceLocation());
2982 MsgExprs.push_back(cnt);
2983
2984
2985 SmallVector<QualType, 8> ArgTypes;
2986 ArgTypes.push_back(Context->getObjCIdType());
2987 ArgTypes.push_back(Context->getObjCSelType());
2988 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2989 E = DictMethod->param_end(); PI != E; ++PI) {
2990 QualType T = (*PI)->getType();
2991 if (const PointerType* PT = T->getAs<PointerType>()) {
2992 QualType PointeeTy = PT->getPointeeType();
2993 convertToUnqualifiedObjCType(PointeeTy);
2994 T = Context->getPointerType(PointeeTy);
2995 }
2996 ArgTypes.push_back(T);
2997 }
2998
2999 QualType returnType = Exp->getType();
3000 // Get the type, we will need to reference it in a couple spots.
3001 QualType msgSendType = MsgSendFlavor->getType();
3002
3003 // Create a reference to the objc_msgSend() declaration.
3004 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3005 VK_LValue, SourceLocation());
3006
3007 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3008 Context->getPointerType(Context->VoidTy),
3009 CK_BitCast, DRE);
3010
3011 // Now do the "normal" pointer to function cast.
3012 QualType castType =
3013 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3014 DictMethod->isVariadic());
3015 castType = Context->getPointerType(castType);
3016 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3017 cast);
3018
3019 // Don't forget the parens to enforce the proper binding.
3020 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3021
3022 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003023 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003024 FT->getResultType(), VK_RValue,
3025 EndLoc);
3026 ReplaceStmt(Exp, CE);
3027 return CE;
3028}
3029
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003030// struct __rw_objc_super {
3031// struct objc_object *object; struct objc_object *superClass;
3032// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003033QualType RewriteModernObjC::getSuperStructType() {
3034 if (!SuperStructDecl) {
3035 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3036 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003037 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003038 QualType FieldTypes[2];
3039
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003040 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003041 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003042 // struct objc_object *superClass;
3043 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003044
3045 // Create fields
3046 for (unsigned i = 0; i < 2; ++i) {
3047 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3048 SourceLocation(),
3049 SourceLocation(), 0,
3050 FieldTypes[i], 0,
3051 /*BitWidth=*/0,
3052 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003053 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003054 }
3055
3056 SuperStructDecl->completeDefinition();
3057 }
3058 return Context->getTagDeclType(SuperStructDecl);
3059}
3060
3061QualType RewriteModernObjC::getConstantStringStructType() {
3062 if (!ConstantStringDecl) {
3063 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3064 SourceLocation(), SourceLocation(),
3065 &Context->Idents.get("__NSConstantStringImpl"));
3066 QualType FieldTypes[4];
3067
3068 // struct objc_object *receiver;
3069 FieldTypes[0] = Context->getObjCIdType();
3070 // int flags;
3071 FieldTypes[1] = Context->IntTy;
3072 // char *str;
3073 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3074 // long length;
3075 FieldTypes[3] = Context->LongTy;
3076
3077 // Create fields
3078 for (unsigned i = 0; i < 4; ++i) {
3079 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3080 ConstantStringDecl,
3081 SourceLocation(),
3082 SourceLocation(), 0,
3083 FieldTypes[i], 0,
3084 /*BitWidth=*/0,
3085 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003086 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003087 }
3088
3089 ConstantStringDecl->completeDefinition();
3090 }
3091 return Context->getTagDeclType(ConstantStringDecl);
3092}
3093
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003094/// getFunctionSourceLocation - returns start location of a function
3095/// definition. Complication arises when function has declared as
3096/// extern "C" or extern "C" {...}
3097static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3098 FunctionDecl *FD) {
3099 if (FD->isExternC() && !FD->isMain()) {
3100 const DeclContext *DC = FD->getDeclContext();
3101 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3102 // if it is extern "C" {...}, return function decl's own location.
3103 if (!LSD->getRBraceLoc().isValid())
3104 return LSD->getExternLoc();
3105 }
3106 if (FD->getStorageClassAsWritten() != SC_None)
3107 R.RewriteBlockLiteralFunctionDecl(FD);
3108 return FD->getTypeSpecStartLoc();
3109}
3110
Fariborz Jahanian96205962012-11-06 17:30:23 +00003111void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3112
3113 SourceLocation Location = D->getLocation();
3114
3115 if (Location.isFileID()) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003116 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003117 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3118 LineString += utostr(PLoc.getLine());
3119 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003120 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003121 if (isa<ObjCMethodDecl>(D))
3122 LineString += "\"";
3123 else LineString += "\"\n";
3124
3125 Location = D->getLocStart();
3126 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3127 if (FD->isExternC() && !FD->isMain()) {
3128 const DeclContext *DC = FD->getDeclContext();
3129 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3130 // if it is extern "C" {...}, return function decl's own location.
3131 if (!LSD->getRBraceLoc().isValid())
3132 Location = LSD->getExternLoc();
3133 }
3134 }
3135 InsertText(Location, LineString);
3136 }
3137}
3138
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003139/// SynthMsgSendStretCallExpr - This routine translates message expression
3140/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3141/// nil check on receiver must be performed before calling objc_msgSend_stret.
3142/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3143/// msgSendType - function type of objc_msgSend_stret(...)
3144/// returnType - Result type of the method being synthesized.
3145/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3146/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3147/// starting with receiver.
3148/// Method - Method being rewritten.
3149Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3150 QualType msgSendType,
3151 QualType returnType,
3152 SmallVectorImpl<QualType> &ArgTypes,
3153 SmallVectorImpl<Expr*> &MsgExprs,
3154 ObjCMethodDecl *Method) {
3155 // Now do the "normal" pointer to function cast.
3156 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3157 Method ? Method->isVariadic() : false);
3158 castType = Context->getPointerType(castType);
3159
3160 // build type for containing the objc_msgSend_stret object.
3161 static unsigned stretCount=0;
3162 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003163 std::string str =
3164 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3165 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003166 str += " {\n\t";
3167 str += name;
3168 str += "(id receiver, SEL sel";
3169 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003170 std::string ArgName = "arg"; ArgName += utostr(i);
3171 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3172 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003173 }
3174 // could be vararg.
3175 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003176 std::string ArgName = "arg"; ArgName += utostr(i);
3177 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3178 Context->getPrintingPolicy());
3179 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003180 }
3181
3182 str += ") {\n";
3183 str += "\t if (receiver == 0)\n";
3184 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3185 str += "\t else\n";
3186 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3187 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3188 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3189 str += ", arg"; str += utostr(i);
3190 }
3191 // could be vararg.
3192 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3193 str += ", arg"; str += utostr(i);
3194 }
3195
3196 str += ");\n";
3197 str += "\t}\n";
3198 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3199 str += " s;\n";
3200 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003201 SourceLocation FunLocStart;
3202 if (CurFunctionDef)
3203 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3204 else {
3205 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3206 FunLocStart = CurMethodDef->getLocStart();
3207 }
3208
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003209 InsertText(FunLocStart, str);
3210 ++stretCount;
3211
3212 // AST for __Stretn(receiver, args).s;
3213 IdentifierInfo *ID = &Context->Idents.get(name);
3214 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3215 SourceLocation(), ID, castType, 0, SC_Extern,
3216 SC_None, false, false);
3217 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3218 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003219 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003220 castType, VK_LValue, SourceLocation());
3221
3222 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3223 SourceLocation(),
3224 &Context->Idents.get("s"),
3225 returnType, 0,
3226 /*BitWidth=*/0, /*Mutable=*/true,
3227 ICIS_NoInit);
3228 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3229 FieldD->getType(), VK_LValue,
3230 OK_Ordinary);
3231
3232 return ME;
3233}
3234
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003235Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3236 SourceLocation StartLoc,
3237 SourceLocation EndLoc) {
3238 if (!SelGetUidFunctionDecl)
3239 SynthSelGetUidFunctionDecl();
3240 if (!MsgSendFunctionDecl)
3241 SynthMsgSendFunctionDecl();
3242 if (!MsgSendSuperFunctionDecl)
3243 SynthMsgSendSuperFunctionDecl();
3244 if (!MsgSendStretFunctionDecl)
3245 SynthMsgSendStretFunctionDecl();
3246 if (!MsgSendSuperStretFunctionDecl)
3247 SynthMsgSendSuperStretFunctionDecl();
3248 if (!MsgSendFpretFunctionDecl)
3249 SynthMsgSendFpretFunctionDecl();
3250 if (!GetClassFunctionDecl)
3251 SynthGetClassFunctionDecl();
3252 if (!GetSuperClassFunctionDecl)
3253 SynthGetSuperClassFunctionDecl();
3254 if (!GetMetaClassFunctionDecl)
3255 SynthGetMetaClassFunctionDecl();
3256
3257 // default to objc_msgSend().
3258 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3259 // May need to use objc_msgSend_stret() as well.
3260 FunctionDecl *MsgSendStretFlavor = 0;
3261 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3262 QualType resultType = mDecl->getResultType();
3263 if (resultType->isRecordType())
3264 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3265 else if (resultType->isRealFloatingType())
3266 MsgSendFlavor = MsgSendFpretFunctionDecl;
3267 }
3268
3269 // Synthesize a call to objc_msgSend().
3270 SmallVector<Expr*, 8> MsgExprs;
3271 switch (Exp->getReceiverKind()) {
3272 case ObjCMessageExpr::SuperClass: {
3273 MsgSendFlavor = MsgSendSuperFunctionDecl;
3274 if (MsgSendStretFlavor)
3275 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3276 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3277
3278 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3279
3280 SmallVector<Expr*, 4> InitExprs;
3281
3282 // set the receiver to self, the first argument to all methods.
3283 InitExprs.push_back(
3284 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3285 CK_BitCast,
3286 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003287 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003288 Context->getObjCIdType(),
3289 VK_RValue,
3290 SourceLocation()))
3291 ); // set the 'receiver'.
3292
3293 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3294 SmallVector<Expr*, 8> ClsExprs;
3295 QualType argType = Context->getPointerType(Context->CharTy);
3296 ClsExprs.push_back(StringLiteral::Create(*Context,
3297 ClassDecl->getIdentifier()->getName(),
3298 StringLiteral::Ascii, false,
3299 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003300 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003301 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3302 &ClsExprs[0],
3303 ClsExprs.size(),
3304 StartLoc,
3305 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003306 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003307 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003308 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3309 &ClsExprs[0], ClsExprs.size(),
3310 StartLoc, EndLoc);
3311
3312 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3313 // To turn off a warning, type-cast to 'id'
3314 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3315 NoTypeInfoCStyleCastExpr(Context,
3316 Context->getObjCIdType(),
3317 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003318 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003319 QualType superType = getSuperStructType();
3320 Expr *SuperRep;
3321
3322 if (LangOpts.MicrosoftExt) {
3323 SynthSuperContructorFunctionDecl();
3324 // Simulate a contructor call...
3325 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003326 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003327 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003328 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003329 superType, VK_LValue,
3330 SourceLocation());
3331 // The code for super is a little tricky to prevent collision with
3332 // the structure definition in the header. The rewriter has it's own
3333 // internal definition (__rw_objc_super) that is uses. This is why
3334 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003335 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003336 //
3337 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3338 Context->getPointerType(SuperRep->getType()),
3339 VK_RValue, OK_Ordinary,
3340 SourceLocation());
3341 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3342 Context->getPointerType(superType),
3343 CK_BitCast, SuperRep);
3344 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003345 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003346 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003347 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003348 SourceLocation());
3349 TypeSourceInfo *superTInfo
3350 = Context->getTrivialTypeSourceInfo(superType);
3351 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3352 superType, VK_LValue,
3353 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003354 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003355 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3356 Context->getPointerType(SuperRep->getType()),
3357 VK_RValue, OK_Ordinary,
3358 SourceLocation());
3359 }
3360 MsgExprs.push_back(SuperRep);
3361 break;
3362 }
3363
3364 case ObjCMessageExpr::Class: {
3365 SmallVector<Expr*, 8> ClsExprs;
3366 QualType argType = Context->getPointerType(Context->CharTy);
3367 ObjCInterfaceDecl *Class
3368 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3369 IdentifierInfo *clsName = Class->getIdentifier();
3370 ClsExprs.push_back(StringLiteral::Create(*Context,
3371 clsName->getName(),
3372 StringLiteral::Ascii, false,
3373 argType, SourceLocation()));
3374 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3375 &ClsExprs[0],
3376 ClsExprs.size(),
3377 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003378 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3379 Context->getObjCIdType(),
3380 CK_BitCast, Cls);
3381 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003382 break;
3383 }
3384
3385 case ObjCMessageExpr::SuperInstance:{
3386 MsgSendFlavor = MsgSendSuperFunctionDecl;
3387 if (MsgSendStretFlavor)
3388 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3389 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3390 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3391 SmallVector<Expr*, 4> InitExprs;
3392
3393 InitExprs.push_back(
3394 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3395 CK_BitCast,
3396 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003397 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003398 Context->getObjCIdType(),
3399 VK_RValue, SourceLocation()))
3400 ); // set the 'receiver'.
3401
3402 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3403 SmallVector<Expr*, 8> ClsExprs;
3404 QualType argType = Context->getPointerType(Context->CharTy);
3405 ClsExprs.push_back(StringLiteral::Create(*Context,
3406 ClassDecl->getIdentifier()->getName(),
3407 StringLiteral::Ascii, false, argType,
3408 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003409 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003410 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3411 &ClsExprs[0],
3412 ClsExprs.size(),
3413 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003414 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003415 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003416 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3417 &ClsExprs[0], ClsExprs.size(),
3418 StartLoc, EndLoc);
3419
3420 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3421 // To turn off a warning, type-cast to 'id'
3422 InitExprs.push_back(
3423 // set 'super class', using class_getSuperclass().
3424 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3425 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003426 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003427 QualType superType = getSuperStructType();
3428 Expr *SuperRep;
3429
3430 if (LangOpts.MicrosoftExt) {
3431 SynthSuperContructorFunctionDecl();
3432 // Simulate a contructor call...
3433 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003434 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003435 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003436 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003437 superType, VK_LValue, SourceLocation());
3438 // The code for super is a little tricky to prevent collision with
3439 // the structure definition in the header. The rewriter has it's own
3440 // internal definition (__rw_objc_super) that is uses. This is why
3441 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003442 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003443 //
3444 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3445 Context->getPointerType(SuperRep->getType()),
3446 VK_RValue, OK_Ordinary,
3447 SourceLocation());
3448 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3449 Context->getPointerType(superType),
3450 CK_BitCast, SuperRep);
3451 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003452 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003453 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003454 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003455 SourceLocation());
3456 TypeSourceInfo *superTInfo
3457 = Context->getTrivialTypeSourceInfo(superType);
3458 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3459 superType, VK_RValue, ILE,
3460 false);
3461 }
3462 MsgExprs.push_back(SuperRep);
3463 break;
3464 }
3465
3466 case ObjCMessageExpr::Instance: {
3467 // Remove all type-casts because it may contain objc-style types; e.g.
3468 // Foo<Proto> *.
3469 Expr *recExpr = Exp->getInstanceReceiver();
3470 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3471 recExpr = CE->getSubExpr();
3472 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3473 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3474 ? CK_BlockPointerToObjCPointerCast
3475 : CK_CPointerToObjCPointerCast;
3476
3477 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3478 CK, recExpr);
3479 MsgExprs.push_back(recExpr);
3480 break;
3481 }
3482 }
3483
3484 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3485 SmallVector<Expr*, 8> SelExprs;
3486 QualType argType = Context->getPointerType(Context->CharTy);
3487 SelExprs.push_back(StringLiteral::Create(*Context,
3488 Exp->getSelector().getAsString(),
3489 StringLiteral::Ascii, false,
3490 argType, SourceLocation()));
3491 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3492 &SelExprs[0], SelExprs.size(),
3493 StartLoc,
3494 EndLoc);
3495 MsgExprs.push_back(SelExp);
3496
3497 // Now push any user supplied arguments.
3498 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3499 Expr *userExpr = Exp->getArg(i);
3500 // Make all implicit casts explicit...ICE comes in handy:-)
3501 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3502 // Reuse the ICE type, it is exactly what the doctor ordered.
3503 QualType type = ICE->getType();
3504 if (needToScanForQualifiers(type))
3505 type = Context->getObjCIdType();
3506 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3507 (void)convertBlockPointerToFunctionPointer(type);
3508 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3509 CastKind CK;
3510 if (SubExpr->getType()->isIntegralType(*Context) &&
3511 type->isBooleanType()) {
3512 CK = CK_IntegralToBoolean;
3513 } else if (type->isObjCObjectPointerType()) {
3514 if (SubExpr->getType()->isBlockPointerType()) {
3515 CK = CK_BlockPointerToObjCPointerCast;
3516 } else if (SubExpr->getType()->isPointerType()) {
3517 CK = CK_CPointerToObjCPointerCast;
3518 } else {
3519 CK = CK_BitCast;
3520 }
3521 } else {
3522 CK = CK_BitCast;
3523 }
3524
3525 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3526 }
3527 // Make id<P...> cast into an 'id' cast.
3528 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3529 if (CE->getType()->isObjCQualifiedIdType()) {
3530 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3531 userExpr = CE->getSubExpr();
3532 CastKind CK;
3533 if (userExpr->getType()->isIntegralType(*Context)) {
3534 CK = CK_IntegralToPointer;
3535 } else if (userExpr->getType()->isBlockPointerType()) {
3536 CK = CK_BlockPointerToObjCPointerCast;
3537 } else if (userExpr->getType()->isPointerType()) {
3538 CK = CK_CPointerToObjCPointerCast;
3539 } else {
3540 CK = CK_BitCast;
3541 }
3542 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3543 CK, userExpr);
3544 }
3545 }
3546 MsgExprs.push_back(userExpr);
3547 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3548 // out the argument in the original expression (since we aren't deleting
3549 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3550 //Exp->setArg(i, 0);
3551 }
3552 // Generate the funky cast.
3553 CastExpr *cast;
3554 SmallVector<QualType, 8> ArgTypes;
3555 QualType returnType;
3556
3557 // Push 'id' and 'SEL', the 2 implicit arguments.
3558 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3559 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3560 else
3561 ArgTypes.push_back(Context->getObjCIdType());
3562 ArgTypes.push_back(Context->getObjCSelType());
3563 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3564 // Push any user argument types.
3565 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3566 E = OMD->param_end(); PI != E; ++PI) {
3567 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3568 ? Context->getObjCIdType()
3569 : (*PI)->getType();
3570 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3571 (void)convertBlockPointerToFunctionPointer(t);
3572 ArgTypes.push_back(t);
3573 }
3574 returnType = Exp->getType();
3575 convertToUnqualifiedObjCType(returnType);
3576 (void)convertBlockPointerToFunctionPointer(returnType);
3577 } else {
3578 returnType = Context->getObjCIdType();
3579 }
3580 // Get the type, we will need to reference it in a couple spots.
3581 QualType msgSendType = MsgSendFlavor->getType();
3582
3583 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003584 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003585 VK_LValue, SourceLocation());
3586
3587 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3588 // If we don't do this cast, we get the following bizarre warning/note:
3589 // xx.m:13: warning: function called through a non-compatible type
3590 // xx.m:13: note: if this code is reached, the program will abort
3591 cast = NoTypeInfoCStyleCastExpr(Context,
3592 Context->getPointerType(Context->VoidTy),
3593 CK_BitCast, DRE);
3594
3595 // Now do the "normal" pointer to function cast.
3596 QualType castType =
3597 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3598 // If we don't have a method decl, force a variadic cast.
3599 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3600 castType = Context->getPointerType(castType);
3601 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3602 cast);
3603
3604 // Don't forget the parens to enforce the proper binding.
3605 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3606
3607 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003608 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3609 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003610 Stmt *ReplacingStmt = CE;
3611 if (MsgSendStretFlavor) {
3612 // We have the method which returns a struct/union. Must also generate
3613 // call to objc_msgSend_stret and hang both varieties on a conditional
3614 // expression which dictate which one to envoke depending on size of
3615 // method's return type.
3616
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003617 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3618 msgSendType, returnType,
3619 ArgTypes, MsgExprs,
3620 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003621
3622 // Build sizeof(returnType)
3623 UnaryExprOrTypeTraitExpr *sizeofExpr =
3624 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3625 Context->getTrivialTypeSourceInfo(returnType),
3626 Context->getSizeType(), SourceLocation(),
3627 SourceLocation());
3628 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3629 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3630 // For X86 it is more complicated and some kind of target specific routine
3631 // is needed to decide what to do.
3632 unsigned IntSize =
3633 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3634 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3635 llvm::APInt(IntSize, 8),
3636 Context->IntTy,
3637 SourceLocation());
3638 BinaryOperator *lessThanExpr =
3639 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003640 VK_RValue, OK_Ordinary, SourceLocation(),
3641 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003642 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3643 ConditionalOperator *CondExpr =
3644 new (Context) ConditionalOperator(lessThanExpr,
3645 SourceLocation(), CE,
3646 SourceLocation(), STCE,
3647 returnType, VK_RValue, OK_Ordinary);
3648 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3649 CondExpr);
3650 }
3651 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3652 return ReplacingStmt;
3653}
3654
3655Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3656 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3657 Exp->getLocEnd());
3658
3659 // Now do the actual rewrite.
3660 ReplaceStmt(Exp, ReplacingStmt);
3661
3662 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3663 return ReplacingStmt;
3664}
3665
3666// typedef struct objc_object Protocol;
3667QualType RewriteModernObjC::getProtocolType() {
3668 if (!ProtocolTypeDecl) {
3669 TypeSourceInfo *TInfo
3670 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3671 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3672 SourceLocation(), SourceLocation(),
3673 &Context->Idents.get("Protocol"),
3674 TInfo);
3675 }
3676 return Context->getTypeDeclType(ProtocolTypeDecl);
3677}
3678
3679/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3680/// a synthesized/forward data reference (to the protocol's metadata).
3681/// The forward references (and metadata) are generated in
3682/// RewriteModernObjC::HandleTranslationUnit().
3683Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003684 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3685 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003686 IdentifierInfo *ID = &Context->Idents.get(Name);
3687 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3688 SourceLocation(), ID, getProtocolType(), 0,
3689 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003690 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3691 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003692 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3693 Context->getPointerType(DRE->getType()),
3694 VK_RValue, OK_Ordinary, SourceLocation());
3695 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3696 CK_BitCast,
3697 DerefExpr);
3698 ReplaceStmt(Exp, castExpr);
3699 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3700 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3701 return castExpr;
3702
3703}
3704
3705bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3706 const char *endBuf) {
3707 while (startBuf < endBuf) {
3708 if (*startBuf == '#') {
3709 // Skip whitespace.
3710 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3711 ;
3712 if (!strncmp(startBuf, "if", strlen("if")) ||
3713 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3714 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3715 !strncmp(startBuf, "define", strlen("define")) ||
3716 !strncmp(startBuf, "undef", strlen("undef")) ||
3717 !strncmp(startBuf, "else", strlen("else")) ||
3718 !strncmp(startBuf, "elif", strlen("elif")) ||
3719 !strncmp(startBuf, "endif", strlen("endif")) ||
3720 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3721 !strncmp(startBuf, "include", strlen("include")) ||
3722 !strncmp(startBuf, "import", strlen("import")) ||
3723 !strncmp(startBuf, "include_next", strlen("include_next")))
3724 return true;
3725 }
3726 startBuf++;
3727 }
3728 return false;
3729}
3730
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003731/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3732/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003733bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003734 TagDecl *Tag,
3735 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003736 if (!IDecl)
3737 return false;
3738 SourceLocation TagLocation;
3739 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3740 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003741 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003742 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003743 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003744 TagLocation = RD->getLocation();
3745 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003746 IDecl->getLocation(), TagLocation);
3747 }
3748 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3749 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3750 return false;
3751 IsNamedDefinition = true;
3752 TagLocation = ED->getLocation();
3753 return Context->getSourceManager().isBeforeInTranslationUnit(
3754 IDecl->getLocation(), TagLocation);
3755
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003756 }
3757 return false;
3758}
3759
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003760/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003761/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003762bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3763 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003764 if (isa<TypedefType>(Type)) {
3765 Result += "\t";
3766 return false;
3767 }
3768
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003769 if (Type->isArrayType()) {
3770 QualType ElemTy = Context->getBaseElementType(Type);
3771 return RewriteObjCFieldDeclType(ElemTy, Result);
3772 }
3773 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003774 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3775 if (RD->isCompleteDefinition()) {
3776 if (RD->isStruct())
3777 Result += "\n\tstruct ";
3778 else if (RD->isUnion())
3779 Result += "\n\tunion ";
3780 else
3781 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003782
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003783 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003784 if (GlobalDefinedTags.count(RD)) {
3785 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003786 Result += " ";
3787 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003788 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003789 Result += " {\n";
3790 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003791 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003792 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003793 RewriteObjCFieldDecl(FD, Result);
3794 }
3795 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003796 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003797 }
3798 }
3799 else if (Type->isEnumeralType()) {
3800 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3801 if (ED->isCompleteDefinition()) {
3802 Result += "\n\tenum ";
3803 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003804 if (GlobalDefinedTags.count(ED)) {
3805 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003806 Result += " ";
3807 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003808 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003809
3810 Result += " {\n";
3811 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3812 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3813 Result += "\t"; Result += EC->getName(); Result += " = ";
3814 llvm::APSInt Val = EC->getInitVal();
3815 Result += Val.toString(10);
3816 Result += ",\n";
3817 }
3818 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003819 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003820 }
3821 }
3822
3823 Result += "\t";
3824 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003825 return false;
3826}
3827
3828
3829/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3830/// It handles elaborated types, as well as enum types in the process.
3831void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3832 std::string &Result) {
3833 QualType Type = fieldDecl->getType();
3834 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003835
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003836 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3837 if (!EleboratedType)
3838 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003839 Result += Name;
3840 if (fieldDecl->isBitField()) {
3841 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3842 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003843 else if (EleboratedType && Type->isArrayType()) {
3844 CanQualType CType = Context->getCanonicalType(Type);
3845 while (isa<ArrayType>(CType)) {
3846 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3847 Result += "[";
3848 llvm::APInt Dim = CAT->getSize();
3849 Result += utostr(Dim.getZExtValue());
3850 Result += "]";
3851 }
3852 CType = CType->getAs<ArrayType>()->getElementType();
3853 }
3854 }
3855
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003856 Result += ";\n";
3857}
3858
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003859/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3860/// named aggregate types into the input buffer.
3861void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3862 std::string &Result) {
3863 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003864 if (isa<TypedefType>(Type))
3865 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003866 if (Type->isArrayType())
3867 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003868 ObjCContainerDecl *IDecl =
3869 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003870
3871 TagDecl *TD = 0;
3872 if (Type->isRecordType()) {
3873 TD = Type->getAs<RecordType>()->getDecl();
3874 }
3875 else if (Type->isEnumeralType()) {
3876 TD = Type->getAs<EnumType>()->getDecl();
3877 }
3878
3879 if (TD) {
3880 if (GlobalDefinedTags.count(TD))
3881 return;
3882
3883 bool IsNamedDefinition = false;
3884 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3885 RewriteObjCFieldDeclType(Type, Result);
3886 Result += ";";
3887 }
3888 if (IsNamedDefinition)
3889 GlobalDefinedTags.insert(TD);
3890 }
3891
3892}
3893
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003894/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3895/// an objective-c class with ivars.
3896void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3897 std::string &Result) {
3898 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3899 assert(CDecl->getName() != "" &&
3900 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003901 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003902 SmallVector<ObjCIvarDecl *, 8> IVars;
3903 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003904 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003905 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003906
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003907 SourceLocation LocStart = CDecl->getLocStart();
3908 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003909
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003910 const char *startBuf = SM->getCharacterData(LocStart);
3911 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003912
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003913 // If no ivars and no root or if its root, directly or indirectly,
3914 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003915 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003916 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3917 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3918 ReplaceText(LocStart, endBuf-startBuf, Result);
3919 return;
3920 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003921
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003922 // Insert named struct/union definitions inside class to
3923 // outer scope. This follows semantics of locally defined
3924 // struct/unions in objective-c classes.
3925 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3926 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3927
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003928 Result += "\nstruct ";
3929 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003930 Result += "_IMPL {\n";
3931
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003932 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003933 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3934 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3935 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003936 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003937
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003938 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3939 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003940
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003941 Result += "};\n";
3942 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3943 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003944 // Mark this struct as having been generated.
3945 if (!ObjCSynthesizedStructs.insert(CDecl))
3946 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003947}
3948
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003949/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3950/// have been referenced in an ivar access expression.
3951void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3952 std::string &Result) {
3953 // write out ivar offset symbols which have been referenced in an ivar
3954 // access expression.
3955 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3956 if (Ivars.empty())
3957 return;
3958 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3959 e = Ivars.end(); i != e; i++) {
3960 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003961 Result += "\n";
3962 if (LangOpts.MicrosoftExt)
3963 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003964 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003965 if (LangOpts.MicrosoftExt &&
3966 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003967 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3968 Result += "__declspec(dllimport) ";
3969
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003970 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003971 WriteInternalIvarName(CDecl, IvarDecl, Result);
3972 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003973 }
3974}
3975
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003976//===----------------------------------------------------------------------===//
3977// Meta Data Emission
3978//===----------------------------------------------------------------------===//
3979
3980
3981/// RewriteImplementations - This routine rewrites all method implementations
3982/// and emits meta-data.
3983
3984void RewriteModernObjC::RewriteImplementations() {
3985 int ClsDefCount = ClassImplementation.size();
3986 int CatDefCount = CategoryImplementation.size();
3987
3988 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003989 for (int i = 0; i < ClsDefCount; i++) {
3990 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3991 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3992 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003993 assert(false &&
3994 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003995 RewriteImplementationDecl(OIMP);
3996 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003997
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003998 for (int i = 0; i < CatDefCount; i++) {
3999 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4000 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4001 if (CDecl->isImplicitInterfaceDecl())
4002 assert(false &&
4003 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004004 RewriteImplementationDecl(CIMP);
4005 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004006}
4007
4008void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4009 const std::string &Name,
4010 ValueDecl *VD, bool def) {
4011 assert(BlockByRefDeclNo.count(VD) &&
4012 "RewriteByRefString: ByRef decl missing");
4013 if (def)
4014 ResultStr += "struct ";
4015 ResultStr += "__Block_byref_" + Name +
4016 "_" + utostr(BlockByRefDeclNo[VD]) ;
4017}
4018
4019static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4020 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4021 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4022 return false;
4023}
4024
4025std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4026 StringRef funcName,
4027 std::string Tag) {
4028 const FunctionType *AFT = CE->getFunctionType();
4029 QualType RT = AFT->getResultType();
4030 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004031 SourceLocation BlockLoc = CE->getExprLoc();
4032 std::string S;
4033 ConvertSourceLocationToLineDirective(BlockLoc, S);
4034
4035 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4036 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004037
4038 BlockDecl *BD = CE->getBlockDecl();
4039
4040 if (isa<FunctionNoProtoType>(AFT)) {
4041 // No user-supplied arguments. Still need to pass in a pointer to the
4042 // block (to reference imported block decl refs).
4043 S += "(" + StructRef + " *__cself)";
4044 } else if (BD->param_empty()) {
4045 S += "(" + StructRef + " *__cself)";
4046 } else {
4047 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4048 assert(FT && "SynthesizeBlockFunc: No function proto");
4049 S += '(';
4050 // first add the implicit argument.
4051 S += StructRef + " *__cself, ";
4052 std::string ParamStr;
4053 for (BlockDecl::param_iterator AI = BD->param_begin(),
4054 E = BD->param_end(); AI != E; ++AI) {
4055 if (AI != BD->param_begin()) S += ", ";
4056 ParamStr = (*AI)->getNameAsString();
4057 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004058 (void)convertBlockPointerToFunctionPointer(QT);
4059 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004060 S += ParamStr;
4061 }
4062 if (FT->isVariadic()) {
4063 if (!BD->param_empty()) S += ", ";
4064 S += "...";
4065 }
4066 S += ')';
4067 }
4068 S += " {\n";
4069
4070 // Create local declarations to avoid rewriting all closure decl ref exprs.
4071 // First, emit a declaration for all "by ref" decls.
4072 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4073 E = BlockByRefDecls.end(); I != E; ++I) {
4074 S += " ";
4075 std::string Name = (*I)->getNameAsString();
4076 std::string TypeString;
4077 RewriteByRefString(TypeString, Name, (*I));
4078 TypeString += " *";
4079 Name = TypeString + Name;
4080 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4081 }
4082 // Next, emit a declaration for all "by copy" declarations.
4083 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4084 E = BlockByCopyDecls.end(); I != E; ++I) {
4085 S += " ";
4086 // Handle nested closure invocation. For example:
4087 //
4088 // void (^myImportedClosure)(void);
4089 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4090 //
4091 // void (^anotherClosure)(void);
4092 // anotherClosure = ^(void) {
4093 // myImportedClosure(); // import and invoke the closure
4094 // };
4095 //
4096 if (isTopLevelBlockPointerType((*I)->getType())) {
4097 RewriteBlockPointerTypeVariable(S, (*I));
4098 S += " = (";
4099 RewriteBlockPointerType(S, (*I)->getType());
4100 S += ")";
4101 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4102 }
4103 else {
4104 std::string Name = (*I)->getNameAsString();
4105 QualType QT = (*I)->getType();
4106 if (HasLocalVariableExternalStorage(*I))
4107 QT = Context->getPointerType(QT);
4108 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4109 S += Name + " = __cself->" +
4110 (*I)->getNameAsString() + "; // bound by copy\n";
4111 }
4112 }
4113 std::string RewrittenStr = RewrittenBlockExprs[CE];
4114 const char *cstr = RewrittenStr.c_str();
4115 while (*cstr++ != '{') ;
4116 S += cstr;
4117 S += "\n";
4118 return S;
4119}
4120
4121std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4122 StringRef funcName,
4123 std::string Tag) {
4124 std::string StructRef = "struct " + Tag;
4125 std::string S = "static void __";
4126
4127 S += funcName;
4128 S += "_block_copy_" + utostr(i);
4129 S += "(" + StructRef;
4130 S += "*dst, " + StructRef;
4131 S += "*src) {";
4132 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4133 E = ImportedBlockDecls.end(); I != E; ++I) {
4134 ValueDecl *VD = (*I);
4135 S += "_Block_object_assign((void*)&dst->";
4136 S += (*I)->getNameAsString();
4137 S += ", (void*)src->";
4138 S += (*I)->getNameAsString();
4139 if (BlockByRefDeclsPtrSet.count((*I)))
4140 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4141 else if (VD->getType()->isBlockPointerType())
4142 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4143 else
4144 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4145 }
4146 S += "}\n";
4147
4148 S += "\nstatic void __";
4149 S += funcName;
4150 S += "_block_dispose_" + utostr(i);
4151 S += "(" + StructRef;
4152 S += "*src) {";
4153 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4154 E = ImportedBlockDecls.end(); I != E; ++I) {
4155 ValueDecl *VD = (*I);
4156 S += "_Block_object_dispose((void*)src->";
4157 S += (*I)->getNameAsString();
4158 if (BlockByRefDeclsPtrSet.count((*I)))
4159 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4160 else if (VD->getType()->isBlockPointerType())
4161 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4162 else
4163 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4164 }
4165 S += "}\n";
4166 return S;
4167}
4168
4169std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4170 std::string Desc) {
4171 std::string S = "\nstruct " + Tag;
4172 std::string Constructor = " " + Tag;
4173
4174 S += " {\n struct __block_impl impl;\n";
4175 S += " struct " + Desc;
4176 S += "* Desc;\n";
4177
4178 Constructor += "(void *fp, "; // Invoke function pointer.
4179 Constructor += "struct " + Desc; // Descriptor pointer.
4180 Constructor += " *desc";
4181
4182 if (BlockDeclRefs.size()) {
4183 // Output all "by copy" declarations.
4184 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4185 E = BlockByCopyDecls.end(); I != E; ++I) {
4186 S += " ";
4187 std::string FieldName = (*I)->getNameAsString();
4188 std::string ArgName = "_" + FieldName;
4189 // Handle nested closure invocation. For example:
4190 //
4191 // void (^myImportedBlock)(void);
4192 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4193 //
4194 // void (^anotherBlock)(void);
4195 // anotherBlock = ^(void) {
4196 // myImportedBlock(); // import and invoke the closure
4197 // };
4198 //
4199 if (isTopLevelBlockPointerType((*I)->getType())) {
4200 S += "struct __block_impl *";
4201 Constructor += ", void *" + ArgName;
4202 } else {
4203 QualType QT = (*I)->getType();
4204 if (HasLocalVariableExternalStorage(*I))
4205 QT = Context->getPointerType(QT);
4206 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4207 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4208 Constructor += ", " + ArgName;
4209 }
4210 S += FieldName + ";\n";
4211 }
4212 // Output all "by ref" declarations.
4213 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4214 E = BlockByRefDecls.end(); I != E; ++I) {
4215 S += " ";
4216 std::string FieldName = (*I)->getNameAsString();
4217 std::string ArgName = "_" + FieldName;
4218 {
4219 std::string TypeString;
4220 RewriteByRefString(TypeString, FieldName, (*I));
4221 TypeString += " *";
4222 FieldName = TypeString + FieldName;
4223 ArgName = TypeString + ArgName;
4224 Constructor += ", " + ArgName;
4225 }
4226 S += FieldName + "; // by ref\n";
4227 }
4228 // Finish writing the constructor.
4229 Constructor += ", int flags=0)";
4230 // Initialize all "by copy" arguments.
4231 bool firsTime = true;
4232 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4233 E = BlockByCopyDecls.end(); I != E; ++I) {
4234 std::string Name = (*I)->getNameAsString();
4235 if (firsTime) {
4236 Constructor += " : ";
4237 firsTime = false;
4238 }
4239 else
4240 Constructor += ", ";
4241 if (isTopLevelBlockPointerType((*I)->getType()))
4242 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4243 else
4244 Constructor += Name + "(_" + Name + ")";
4245 }
4246 // Initialize all "by ref" arguments.
4247 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4248 E = BlockByRefDecls.end(); I != E; ++I) {
4249 std::string Name = (*I)->getNameAsString();
4250 if (firsTime) {
4251 Constructor += " : ";
4252 firsTime = false;
4253 }
4254 else
4255 Constructor += ", ";
4256 Constructor += Name + "(_" + Name + "->__forwarding)";
4257 }
4258
4259 Constructor += " {\n";
4260 if (GlobalVarDecl)
4261 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4262 else
4263 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4264 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4265
4266 Constructor += " Desc = desc;\n";
4267 } else {
4268 // Finish writing the constructor.
4269 Constructor += ", int flags=0) {\n";
4270 if (GlobalVarDecl)
4271 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4272 else
4273 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4274 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4275 Constructor += " Desc = desc;\n";
4276 }
4277 Constructor += " ";
4278 Constructor += "}\n";
4279 S += Constructor;
4280 S += "};\n";
4281 return S;
4282}
4283
4284std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4285 std::string ImplTag, int i,
4286 StringRef FunName,
4287 unsigned hasCopy) {
4288 std::string S = "\nstatic struct " + DescTag;
4289
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004290 S += " {\n size_t reserved;\n";
4291 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004292 if (hasCopy) {
4293 S += " void (*copy)(struct ";
4294 S += ImplTag; S += "*, struct ";
4295 S += ImplTag; S += "*);\n";
4296
4297 S += " void (*dispose)(struct ";
4298 S += ImplTag; S += "*);\n";
4299 }
4300 S += "} ";
4301
4302 S += DescTag + "_DATA = { 0, sizeof(struct ";
4303 S += ImplTag + ")";
4304 if (hasCopy) {
4305 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4306 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4307 }
4308 S += "};\n";
4309 return S;
4310}
4311
4312void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4313 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004314 bool RewriteSC = (GlobalVarDecl &&
4315 !Blocks.empty() &&
4316 GlobalVarDecl->getStorageClass() == SC_Static &&
4317 GlobalVarDecl->getType().getCVRQualifiers());
4318 if (RewriteSC) {
4319 std::string SC(" void __");
4320 SC += GlobalVarDecl->getNameAsString();
4321 SC += "() {}";
4322 InsertText(FunLocStart, SC);
4323 }
4324
4325 // Insert closures that were part of the function.
4326 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4327 CollectBlockDeclRefInfo(Blocks[i]);
4328 // Need to copy-in the inner copied-in variables not actually used in this
4329 // block.
4330 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004331 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004332 ValueDecl *VD = Exp->getDecl();
4333 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004334 if (!VD->hasAttr<BlocksAttr>()) {
4335 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4336 BlockByCopyDeclsPtrSet.insert(VD);
4337 BlockByCopyDecls.push_back(VD);
4338 }
4339 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004340 }
John McCallf4b88a42012-03-10 09:33:50 +00004341
4342 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004343 BlockByRefDeclsPtrSet.insert(VD);
4344 BlockByRefDecls.push_back(VD);
4345 }
John McCallf4b88a42012-03-10 09:33:50 +00004346
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004347 // imported objects in the inner blocks not used in the outer
4348 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004349 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004350 VD->getType()->isBlockPointerType())
4351 ImportedBlockDecls.insert(VD);
4352 }
4353
4354 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4355 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4356
4357 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4358
4359 InsertText(FunLocStart, CI);
4360
4361 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4362
4363 InsertText(FunLocStart, CF);
4364
4365 if (ImportedBlockDecls.size()) {
4366 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4367 InsertText(FunLocStart, HF);
4368 }
4369 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4370 ImportedBlockDecls.size() > 0);
4371 InsertText(FunLocStart, BD);
4372
4373 BlockDeclRefs.clear();
4374 BlockByRefDecls.clear();
4375 BlockByRefDeclsPtrSet.clear();
4376 BlockByCopyDecls.clear();
4377 BlockByCopyDeclsPtrSet.clear();
4378 ImportedBlockDecls.clear();
4379 }
4380 if (RewriteSC) {
4381 // Must insert any 'const/volatile/static here. Since it has been
4382 // removed as result of rewriting of block literals.
4383 std::string SC;
4384 if (GlobalVarDecl->getStorageClass() == SC_Static)
4385 SC = "static ";
4386 if (GlobalVarDecl->getType().isConstQualified())
4387 SC += "const ";
4388 if (GlobalVarDecl->getType().isVolatileQualified())
4389 SC += "volatile ";
4390 if (GlobalVarDecl->getType().isRestrictQualified())
4391 SC += "restrict ";
4392 InsertText(FunLocStart, SC);
4393 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004394 if (GlobalConstructionExp) {
4395 // extra fancy dance for global literal expression.
4396
4397 // Always the latest block expression on the block stack.
4398 std::string Tag = "__";
4399 Tag += FunName;
4400 Tag += "_block_impl_";
4401 Tag += utostr(Blocks.size()-1);
4402 std::string globalBuf = "static ";
4403 globalBuf += Tag; globalBuf += " ";
4404 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004405
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004406 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004407 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004408 PrintingPolicy(LangOpts));
4409 globalBuf += constructorExprBuf.str();
4410 globalBuf += ";\n";
4411 InsertText(FunLocStart, globalBuf);
4412 GlobalConstructionExp = 0;
4413 }
4414
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004415 Blocks.clear();
4416 InnerDeclRefsCount.clear();
4417 InnerDeclRefs.clear();
4418 RewrittenBlockExprs.clear();
4419}
4420
4421void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004422 SourceLocation FunLocStart =
4423 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4424 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004425 StringRef FuncName = FD->getName();
4426
4427 SynthesizeBlockLiterals(FunLocStart, FuncName);
4428}
4429
4430static void BuildUniqueMethodName(std::string &Name,
4431 ObjCMethodDecl *MD) {
4432 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4433 Name = IFace->getName();
4434 Name += "__" + MD->getSelector().getAsString();
4435 // Convert colons to underscores.
4436 std::string::size_type loc = 0;
4437 while ((loc = Name.find(":", loc)) != std::string::npos)
4438 Name.replace(loc, 1, "_");
4439}
4440
4441void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4442 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4443 //SourceLocation FunLocStart = MD->getLocStart();
4444 SourceLocation FunLocStart = MD->getLocStart();
4445 std::string FuncName;
4446 BuildUniqueMethodName(FuncName, MD);
4447 SynthesizeBlockLiterals(FunLocStart, FuncName);
4448}
4449
4450void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4451 for (Stmt::child_range CI = S->children(); CI; ++CI)
4452 if (*CI) {
4453 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4454 GetBlockDeclRefExprs(CBE->getBody());
4455 else
4456 GetBlockDeclRefExprs(*CI);
4457 }
4458 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004459 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4460 if (DRE->refersToEnclosingLocal()) {
4461 // FIXME: Handle enums.
4462 if (!isa<FunctionDecl>(DRE->getDecl()))
4463 BlockDeclRefs.push_back(DRE);
4464 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4465 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004466 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004467 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004468
4469 return;
4470}
4471
4472void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004473 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004474 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4475 for (Stmt::child_range CI = S->children(); CI; ++CI)
4476 if (*CI) {
4477 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4478 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4479 GetInnerBlockDeclRefExprs(CBE->getBody(),
4480 InnerBlockDeclRefs,
4481 InnerContexts);
4482 }
4483 else
4484 GetInnerBlockDeclRefExprs(*CI,
4485 InnerBlockDeclRefs,
4486 InnerContexts);
4487
4488 }
4489 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004490 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4491 if (DRE->refersToEnclosingLocal()) {
4492 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4493 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4494 InnerBlockDeclRefs.push_back(DRE);
4495 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4496 if (Var->isFunctionOrMethodVarDecl())
4497 ImportedLocalExternalDecls.insert(Var);
4498 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004499 }
4500
4501 return;
4502}
4503
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004504/// convertObjCTypeToCStyleType - This routine converts such objc types
4505/// as qualified objects, and blocks to their closest c/c++ types that
4506/// it can. It returns true if input type was modified.
4507bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4508 QualType oldT = T;
4509 convertBlockPointerToFunctionPointer(T);
4510 if (T->isFunctionPointerType()) {
4511 QualType PointeeTy;
4512 if (const PointerType* PT = T->getAs<PointerType>()) {
4513 PointeeTy = PT->getPointeeType();
4514 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4515 T = convertFunctionTypeOfBlocks(FT);
4516 T = Context->getPointerType(T);
4517 }
4518 }
4519 }
4520
4521 convertToUnqualifiedObjCType(T);
4522 return T != oldT;
4523}
4524
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004525/// convertFunctionTypeOfBlocks - This routine converts a function type
4526/// whose result type may be a block pointer or whose argument type(s)
4527/// might be block pointers to an equivalent function type replacing
4528/// all block pointers to function pointers.
4529QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4530 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4531 // FTP will be null for closures that don't take arguments.
4532 // Generate a funky cast.
4533 SmallVector<QualType, 8> ArgTypes;
4534 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004535 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004536
4537 if (FTP) {
4538 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4539 E = FTP->arg_type_end(); I && (I != E); ++I) {
4540 QualType t = *I;
4541 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004542 if (convertObjCTypeToCStyleType(t))
4543 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004544 ArgTypes.push_back(t);
4545 }
4546 }
4547 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004548 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004549 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4550 else FuncType = QualType(FT, 0);
4551 return FuncType;
4552}
4553
4554Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4555 // Navigate to relevant type information.
4556 const BlockPointerType *CPT = 0;
4557
4558 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4559 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004560 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4561 CPT = MExpr->getType()->getAs<BlockPointerType>();
4562 }
4563 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4564 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4565 }
4566 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4567 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4568 else if (const ConditionalOperator *CEXPR =
4569 dyn_cast<ConditionalOperator>(BlockExp)) {
4570 Expr *LHSExp = CEXPR->getLHS();
4571 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4572 Expr *RHSExp = CEXPR->getRHS();
4573 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4574 Expr *CONDExp = CEXPR->getCond();
4575 ConditionalOperator *CondExpr =
4576 new (Context) ConditionalOperator(CONDExp,
4577 SourceLocation(), cast<Expr>(LHSStmt),
4578 SourceLocation(), cast<Expr>(RHSStmt),
4579 Exp->getType(), VK_RValue, OK_Ordinary);
4580 return CondExpr;
4581 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4582 CPT = IRE->getType()->getAs<BlockPointerType>();
4583 } else if (const PseudoObjectExpr *POE
4584 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4585 CPT = POE->getType()->castAs<BlockPointerType>();
4586 } else {
4587 assert(1 && "RewriteBlockClass: Bad type");
4588 }
4589 assert(CPT && "RewriteBlockClass: Bad type");
4590 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4591 assert(FT && "RewriteBlockClass: Bad type");
4592 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4593 // FTP will be null for closures that don't take arguments.
4594
4595 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4596 SourceLocation(), SourceLocation(),
4597 &Context->Idents.get("__block_impl"));
4598 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4599
4600 // Generate a funky cast.
4601 SmallVector<QualType, 8> ArgTypes;
4602
4603 // Push the block argument type.
4604 ArgTypes.push_back(PtrBlock);
4605 if (FTP) {
4606 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4607 E = FTP->arg_type_end(); I && (I != E); ++I) {
4608 QualType t = *I;
4609 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4610 if (!convertBlockPointerToFunctionPointer(t))
4611 convertToUnqualifiedObjCType(t);
4612 ArgTypes.push_back(t);
4613 }
4614 }
4615 // Now do the pointer to function cast.
4616 QualType PtrToFuncCastType
4617 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4618
4619 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4620
4621 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4622 CK_BitCast,
4623 const_cast<Expr*>(BlockExp));
4624 // Don't forget the parens to enforce the proper binding.
4625 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4626 BlkCast);
4627 //PE->dump();
4628
4629 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4630 SourceLocation(),
4631 &Context->Idents.get("FuncPtr"),
4632 Context->VoidPtrTy, 0,
4633 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004634 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004635 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4636 FD->getType(), VK_LValue,
4637 OK_Ordinary);
4638
4639
4640 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4641 CK_BitCast, ME);
4642 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4643
4644 SmallVector<Expr*, 8> BlkExprs;
4645 // Add the implicit argument.
4646 BlkExprs.push_back(BlkCast);
4647 // Add the user arguments.
4648 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4649 E = Exp->arg_end(); I != E; ++I) {
4650 BlkExprs.push_back(*I);
4651 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004652 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004653 Exp->getType(), VK_RValue,
4654 SourceLocation());
4655 return CE;
4656}
4657
4658// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004659// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004660// For example:
4661//
4662// int main() {
4663// __block Foo *f;
4664// __block int i;
4665//
4666// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004667// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004668// i = 77;
4669// };
4670//}
John McCallf4b88a42012-03-10 09:33:50 +00004671Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004672 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4673 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004674 ValueDecl *VD = DeclRefExp->getDecl();
4675 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004676
4677 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4678 SourceLocation(),
4679 &Context->Idents.get("__forwarding"),
4680 Context->VoidPtrTy, 0,
4681 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004682 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004683 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4684 FD, SourceLocation(),
4685 FD->getType(), VK_LValue,
4686 OK_Ordinary);
4687
4688 StringRef Name = VD->getName();
4689 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4690 &Context->Idents.get(Name),
4691 Context->VoidPtrTy, 0,
4692 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004693 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004694 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4695 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4696
4697
4698
4699 // Need parens to enforce precedence.
4700 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4701 DeclRefExp->getExprLoc(),
4702 ME);
4703 ReplaceStmt(DeclRefExp, PE);
4704 return PE;
4705}
4706
4707// Rewrites the imported local variable V with external storage
4708// (static, extern, etc.) as *V
4709//
4710Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4711 ValueDecl *VD = DRE->getDecl();
4712 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4713 if (!ImportedLocalExternalDecls.count(Var))
4714 return DRE;
4715 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4716 VK_LValue, OK_Ordinary,
4717 DRE->getLocation());
4718 // Need parens to enforce precedence.
4719 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4720 Exp);
4721 ReplaceStmt(DRE, PE);
4722 return PE;
4723}
4724
4725void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4726 SourceLocation LocStart = CE->getLParenLoc();
4727 SourceLocation LocEnd = CE->getRParenLoc();
4728
4729 // Need to avoid trying to rewrite synthesized casts.
4730 if (LocStart.isInvalid())
4731 return;
4732 // Need to avoid trying to rewrite casts contained in macros.
4733 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4734 return;
4735
4736 const char *startBuf = SM->getCharacterData(LocStart);
4737 const char *endBuf = SM->getCharacterData(LocEnd);
4738 QualType QT = CE->getType();
4739 const Type* TypePtr = QT->getAs<Type>();
4740 if (isa<TypeOfExprType>(TypePtr)) {
4741 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4742 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4743 std::string TypeAsString = "(";
4744 RewriteBlockPointerType(TypeAsString, QT);
4745 TypeAsString += ")";
4746 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4747 return;
4748 }
4749 // advance the location to startArgList.
4750 const char *argPtr = startBuf;
4751
4752 while (*argPtr++ && (argPtr < endBuf)) {
4753 switch (*argPtr) {
4754 case '^':
4755 // Replace the '^' with '*'.
4756 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4757 ReplaceText(LocStart, 1, "*");
4758 break;
4759 }
4760 }
4761 return;
4762}
4763
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004764void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4765 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004766 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4767 CastKind != CK_AnyPointerToBlockPointerCast)
4768 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004769
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004770 QualType QT = IC->getType();
4771 (void)convertBlockPointerToFunctionPointer(QT);
4772 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4773 std::string Str = "(";
4774 Str += TypeString;
4775 Str += ")";
4776 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4777
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004778 return;
4779}
4780
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004781void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4782 SourceLocation DeclLoc = FD->getLocation();
4783 unsigned parenCount = 0;
4784
4785 // We have 1 or more arguments that have closure pointers.
4786 const char *startBuf = SM->getCharacterData(DeclLoc);
4787 const char *startArgList = strchr(startBuf, '(');
4788
4789 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4790
4791 parenCount++;
4792 // advance the location to startArgList.
4793 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4794 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4795
4796 const char *argPtr = startArgList;
4797
4798 while (*argPtr++ && parenCount) {
4799 switch (*argPtr) {
4800 case '^':
4801 // Replace the '^' with '*'.
4802 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4803 ReplaceText(DeclLoc, 1, "*");
4804 break;
4805 case '(':
4806 parenCount++;
4807 break;
4808 case ')':
4809 parenCount--;
4810 break;
4811 }
4812 }
4813 return;
4814}
4815
4816bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4817 const FunctionProtoType *FTP;
4818 const PointerType *PT = QT->getAs<PointerType>();
4819 if (PT) {
4820 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4821 } else {
4822 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4823 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4824 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4825 }
4826 if (FTP) {
4827 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4828 E = FTP->arg_type_end(); I != E; ++I)
4829 if (isTopLevelBlockPointerType(*I))
4830 return true;
4831 }
4832 return false;
4833}
4834
4835bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4836 const FunctionProtoType *FTP;
4837 const PointerType *PT = QT->getAs<PointerType>();
4838 if (PT) {
4839 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4840 } else {
4841 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4842 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4843 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4844 }
4845 if (FTP) {
4846 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4847 E = FTP->arg_type_end(); I != E; ++I) {
4848 if ((*I)->isObjCQualifiedIdType())
4849 return true;
4850 if ((*I)->isObjCObjectPointerType() &&
4851 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4852 return true;
4853 }
4854
4855 }
4856 return false;
4857}
4858
4859void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4860 const char *&RParen) {
4861 const char *argPtr = strchr(Name, '(');
4862 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4863
4864 LParen = argPtr; // output the start.
4865 argPtr++; // skip past the left paren.
4866 unsigned parenCount = 1;
4867
4868 while (*argPtr && parenCount) {
4869 switch (*argPtr) {
4870 case '(': parenCount++; break;
4871 case ')': parenCount--; break;
4872 default: break;
4873 }
4874 if (parenCount) argPtr++;
4875 }
4876 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4877 RParen = argPtr; // output the end
4878}
4879
4880void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4881 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4882 RewriteBlockPointerFunctionArgs(FD);
4883 return;
4884 }
4885 // Handle Variables and Typedefs.
4886 SourceLocation DeclLoc = ND->getLocation();
4887 QualType DeclT;
4888 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4889 DeclT = VD->getType();
4890 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4891 DeclT = TDD->getUnderlyingType();
4892 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4893 DeclT = FD->getType();
4894 else
4895 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4896
4897 const char *startBuf = SM->getCharacterData(DeclLoc);
4898 const char *endBuf = startBuf;
4899 // scan backward (from the decl location) for the end of the previous decl.
4900 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4901 startBuf--;
4902 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4903 std::string buf;
4904 unsigned OrigLength=0;
4905 // *startBuf != '^' if we are dealing with a pointer to function that
4906 // may take block argument types (which will be handled below).
4907 if (*startBuf == '^') {
4908 // Replace the '^' with '*', computing a negative offset.
4909 buf = '*';
4910 startBuf++;
4911 OrigLength++;
4912 }
4913 while (*startBuf != ')') {
4914 buf += *startBuf;
4915 startBuf++;
4916 OrigLength++;
4917 }
4918 buf += ')';
4919 OrigLength++;
4920
4921 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4922 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4923 // Replace the '^' with '*' for arguments.
4924 // Replace id<P> with id/*<>*/
4925 DeclLoc = ND->getLocation();
4926 startBuf = SM->getCharacterData(DeclLoc);
4927 const char *argListBegin, *argListEnd;
4928 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4929 while (argListBegin < argListEnd) {
4930 if (*argListBegin == '^')
4931 buf += '*';
4932 else if (*argListBegin == '<') {
4933 buf += "/*";
4934 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004935 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004936 while (*argListBegin != '>') {
4937 buf += *argListBegin++;
4938 OrigLength++;
4939 }
4940 buf += *argListBegin;
4941 buf += "*/";
4942 }
4943 else
4944 buf += *argListBegin;
4945 argListBegin++;
4946 OrigLength++;
4947 }
4948 buf += ')';
4949 OrigLength++;
4950 }
4951 ReplaceText(Start, OrigLength, buf);
4952
4953 return;
4954}
4955
4956
4957/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4958/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4959/// struct Block_byref_id_object *src) {
4960/// _Block_object_assign (&_dest->object, _src->object,
4961/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4962/// [|BLOCK_FIELD_IS_WEAK]) // object
4963/// _Block_object_assign(&_dest->object, _src->object,
4964/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4965/// [|BLOCK_FIELD_IS_WEAK]) // block
4966/// }
4967/// And:
4968/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4969/// _Block_object_dispose(_src->object,
4970/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4971/// [|BLOCK_FIELD_IS_WEAK]) // object
4972/// _Block_object_dispose(_src->object,
4973/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4974/// [|BLOCK_FIELD_IS_WEAK]) // block
4975/// }
4976
4977std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4978 int flag) {
4979 std::string S;
4980 if (CopyDestroyCache.count(flag))
4981 return S;
4982 CopyDestroyCache.insert(flag);
4983 S = "static void __Block_byref_id_object_copy_";
4984 S += utostr(flag);
4985 S += "(void *dst, void *src) {\n";
4986
4987 // offset into the object pointer is computed as:
4988 // void * + void* + int + int + void* + void *
4989 unsigned IntSize =
4990 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4991 unsigned VoidPtrSize =
4992 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4993
4994 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4995 S += " _Block_object_assign((char*)dst + ";
4996 S += utostr(offset);
4997 S += ", *(void * *) ((char*)src + ";
4998 S += utostr(offset);
4999 S += "), ";
5000 S += utostr(flag);
5001 S += ");\n}\n";
5002
5003 S += "static void __Block_byref_id_object_dispose_";
5004 S += utostr(flag);
5005 S += "(void *src) {\n";
5006 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5007 S += utostr(offset);
5008 S += "), ";
5009 S += utostr(flag);
5010 S += ");\n}\n";
5011 return S;
5012}
5013
5014/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5015/// the declaration into:
5016/// struct __Block_byref_ND {
5017/// void *__isa; // NULL for everything except __weak pointers
5018/// struct __Block_byref_ND *__forwarding;
5019/// int32_t __flags;
5020/// int32_t __size;
5021/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5022/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5023/// typex ND;
5024/// };
5025///
5026/// It then replaces declaration of ND variable with:
5027/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5028/// __size=sizeof(struct __Block_byref_ND),
5029/// ND=initializer-if-any};
5030///
5031///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005032void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5033 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005034 int flag = 0;
5035 int isa = 0;
5036 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5037 if (DeclLoc.isInvalid())
5038 // If type location is missing, it is because of missing type (a warning).
5039 // Use variable's location which is good for this case.
5040 DeclLoc = ND->getLocation();
5041 const char *startBuf = SM->getCharacterData(DeclLoc);
5042 SourceLocation X = ND->getLocEnd();
5043 X = SM->getExpansionLoc(X);
5044 const char *endBuf = SM->getCharacterData(X);
5045 std::string Name(ND->getNameAsString());
5046 std::string ByrefType;
5047 RewriteByRefString(ByrefType, Name, ND, true);
5048 ByrefType += " {\n";
5049 ByrefType += " void *__isa;\n";
5050 RewriteByRefString(ByrefType, Name, ND);
5051 ByrefType += " *__forwarding;\n";
5052 ByrefType += " int __flags;\n";
5053 ByrefType += " int __size;\n";
5054 // Add void *__Block_byref_id_object_copy;
5055 // void *__Block_byref_id_object_dispose; if needed.
5056 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005057 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005058 if (HasCopyAndDispose) {
5059 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5060 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5061 }
5062
5063 QualType T = Ty;
5064 (void)convertBlockPointerToFunctionPointer(T);
5065 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5066
5067 ByrefType += " " + Name + ";\n";
5068 ByrefType += "};\n";
5069 // Insert this type in global scope. It is needed by helper function.
5070 SourceLocation FunLocStart;
5071 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005072 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005073 else {
5074 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5075 FunLocStart = CurMethodDef->getLocStart();
5076 }
5077 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005078
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005079 if (Ty.isObjCGCWeak()) {
5080 flag |= BLOCK_FIELD_IS_WEAK;
5081 isa = 1;
5082 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005083 if (HasCopyAndDispose) {
5084 flag = BLOCK_BYREF_CALLER;
5085 QualType Ty = ND->getType();
5086 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5087 if (Ty->isBlockPointerType())
5088 flag |= BLOCK_FIELD_IS_BLOCK;
5089 else
5090 flag |= BLOCK_FIELD_IS_OBJECT;
5091 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5092 if (!HF.empty())
5093 InsertText(FunLocStart, HF);
5094 }
5095
5096 // struct __Block_byref_ND ND =
5097 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5098 // initializer-if-any};
5099 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005100 // FIXME. rewriter does not support __block c++ objects which
5101 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005102 if (hasInit)
5103 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5104 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5105 if (CXXDecl && CXXDecl->isDefaultConstructor())
5106 hasInit = false;
5107 }
5108
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005109 unsigned flags = 0;
5110 if (HasCopyAndDispose)
5111 flags |= BLOCK_HAS_COPY_DISPOSE;
5112 Name = ND->getNameAsString();
5113 ByrefType.clear();
5114 RewriteByRefString(ByrefType, Name, ND);
5115 std::string ForwardingCastType("(");
5116 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005117 ByrefType += " " + Name + " = {(void*)";
5118 ByrefType += utostr(isa);
5119 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5120 ByrefType += utostr(flags);
5121 ByrefType += ", ";
5122 ByrefType += "sizeof(";
5123 RewriteByRefString(ByrefType, Name, ND);
5124 ByrefType += ")";
5125 if (HasCopyAndDispose) {
5126 ByrefType += ", __Block_byref_id_object_copy_";
5127 ByrefType += utostr(flag);
5128 ByrefType += ", __Block_byref_id_object_dispose_";
5129 ByrefType += utostr(flag);
5130 }
5131
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005132 if (!firstDecl) {
5133 // In multiple __block declarations, and for all but 1st declaration,
5134 // find location of the separating comma. This would be start location
5135 // where new text is to be inserted.
5136 DeclLoc = ND->getLocation();
5137 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5138 const char *commaBuf = startDeclBuf;
5139 while (*commaBuf != ',')
5140 commaBuf--;
5141 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5142 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5143 startBuf = commaBuf;
5144 }
5145
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005146 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005147 ByrefType += "};\n";
5148 unsigned nameSize = Name.size();
5149 // for block or function pointer declaration. Name is aleady
5150 // part of the declaration.
5151 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5152 nameSize = 1;
5153 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5154 }
5155 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005156 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005157 SourceLocation startLoc;
5158 Expr *E = ND->getInit();
5159 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5160 startLoc = ECE->getLParenLoc();
5161 else
5162 startLoc = E->getLocStart();
5163 startLoc = SM->getExpansionLoc(startLoc);
5164 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005165 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005166
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005167 const char separator = lastDecl ? ';' : ',';
5168 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5169 const char *separatorBuf = strchr(startInitializerBuf, separator);
5170 assert((*separatorBuf == separator) &&
5171 "RewriteByRefVar: can't find ';' or ','");
5172 SourceLocation separatorLoc =
5173 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5174
5175 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005176 }
5177 return;
5178}
5179
5180void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5181 // Add initializers for any closure decl refs.
5182 GetBlockDeclRefExprs(Exp->getBody());
5183 if (BlockDeclRefs.size()) {
5184 // Unique all "by copy" declarations.
5185 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005186 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005187 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5188 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5189 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5190 }
5191 }
5192 // Unique all "by ref" declarations.
5193 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005194 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005195 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5196 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5197 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5198 }
5199 }
5200 // Find any imported blocks...they will need special attention.
5201 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005202 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005203 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5204 BlockDeclRefs[i]->getType()->isBlockPointerType())
5205 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5206 }
5207}
5208
5209FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5210 IdentifierInfo *ID = &Context->Idents.get(name);
5211 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5212 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5213 SourceLocation(), ID, FType, 0, SC_Extern,
5214 SC_None, false, false);
5215}
5216
5217Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005218 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005219
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005220 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005221
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005222 Blocks.push_back(Exp);
5223
5224 CollectBlockDeclRefInfo(Exp);
5225
5226 // Add inner imported variables now used in current block.
5227 int countOfInnerDecls = 0;
5228 if (!InnerBlockDeclRefs.empty()) {
5229 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005230 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005231 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005232 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005233 // We need to save the copied-in variables in nested
5234 // blocks because it is needed at the end for some of the API generations.
5235 // See SynthesizeBlockLiterals routine.
5236 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5237 BlockDeclRefs.push_back(Exp);
5238 BlockByCopyDeclsPtrSet.insert(VD);
5239 BlockByCopyDecls.push_back(VD);
5240 }
John McCallf4b88a42012-03-10 09:33:50 +00005241 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005242 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5243 BlockDeclRefs.push_back(Exp);
5244 BlockByRefDeclsPtrSet.insert(VD);
5245 BlockByRefDecls.push_back(VD);
5246 }
5247 }
5248 // Find any imported blocks...they will need special attention.
5249 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005250 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005251 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5252 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5253 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5254 }
5255 InnerDeclRefsCount.push_back(countOfInnerDecls);
5256
5257 std::string FuncName;
5258
5259 if (CurFunctionDef)
5260 FuncName = CurFunctionDef->getNameAsString();
5261 else if (CurMethodDef)
5262 BuildUniqueMethodName(FuncName, CurMethodDef);
5263 else if (GlobalVarDecl)
5264 FuncName = std::string(GlobalVarDecl->getNameAsString());
5265
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005266 bool GlobalBlockExpr =
5267 block->getDeclContext()->getRedeclContext()->isFileContext();
5268
5269 if (GlobalBlockExpr && !GlobalVarDecl) {
5270 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5271 GlobalBlockExpr = false;
5272 }
5273
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005274 std::string BlockNumber = utostr(Blocks.size()-1);
5275
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005276 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5277
5278 // Get a pointer to the function type so we can cast appropriately.
5279 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5280 QualType FType = Context->getPointerType(BFT);
5281
5282 FunctionDecl *FD;
5283 Expr *NewRep;
5284
5285 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005286 std::string Tag;
5287
5288 if (GlobalBlockExpr)
5289 Tag = "__global_";
5290 else
5291 Tag = "__";
5292 Tag += FuncName + "_block_impl_" + BlockNumber;
5293
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005294 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005295 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005296 SourceLocation());
5297
5298 SmallVector<Expr*, 4> InitExprs;
5299
5300 // Initialize the block function.
5301 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005302 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5303 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005304 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5305 CK_BitCast, Arg);
5306 InitExprs.push_back(castExpr);
5307
5308 // Initialize the block descriptor.
5309 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5310
5311 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5312 SourceLocation(), SourceLocation(),
5313 &Context->Idents.get(DescData.c_str()),
5314 Context->VoidPtrTy, 0,
5315 SC_Static, SC_None);
5316 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005317 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005318 Context->VoidPtrTy,
5319 VK_LValue,
5320 SourceLocation()),
5321 UO_AddrOf,
5322 Context->getPointerType(Context->VoidPtrTy),
5323 VK_RValue, OK_Ordinary,
5324 SourceLocation());
5325 InitExprs.push_back(DescRefExpr);
5326
5327 // Add initializers for any closure decl refs.
5328 if (BlockDeclRefs.size()) {
5329 Expr *Exp;
5330 // Output all "by copy" declarations.
5331 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5332 E = BlockByCopyDecls.end(); I != E; ++I) {
5333 if (isObjCType((*I)->getType())) {
5334 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5335 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005336 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5337 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005338 if (HasLocalVariableExternalStorage(*I)) {
5339 QualType QT = (*I)->getType();
5340 QT = Context->getPointerType(QT);
5341 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5342 OK_Ordinary, SourceLocation());
5343 }
5344 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5345 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005346 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5347 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005348 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5349 CK_BitCast, Arg);
5350 } else {
5351 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005352 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5353 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005354 if (HasLocalVariableExternalStorage(*I)) {
5355 QualType QT = (*I)->getType();
5356 QT = Context->getPointerType(QT);
5357 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5358 OK_Ordinary, SourceLocation());
5359 }
5360
5361 }
5362 InitExprs.push_back(Exp);
5363 }
5364 // Output all "by ref" declarations.
5365 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5366 E = BlockByRefDecls.end(); I != E; ++I) {
5367 ValueDecl *ND = (*I);
5368 std::string Name(ND->getNameAsString());
5369 std::string RecName;
5370 RewriteByRefString(RecName, Name, ND, true);
5371 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5372 + sizeof("struct"));
5373 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5374 SourceLocation(), SourceLocation(),
5375 II);
5376 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5377 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5378
5379 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005380 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005381 SourceLocation());
5382 bool isNestedCapturedVar = false;
5383 if (block)
5384 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5385 ce = block->capture_end(); ci != ce; ++ci) {
5386 const VarDecl *variable = ci->getVariable();
5387 if (variable == ND && ci->isNested()) {
5388 assert (ci->isByRef() &&
5389 "SynthBlockInitExpr - captured block variable is not byref");
5390 isNestedCapturedVar = true;
5391 break;
5392 }
5393 }
5394 // captured nested byref variable has its address passed. Do not take
5395 // its address again.
5396 if (!isNestedCapturedVar)
5397 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5398 Context->getPointerType(Exp->getType()),
5399 VK_RValue, OK_Ordinary, SourceLocation());
5400 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5401 InitExprs.push_back(Exp);
5402 }
5403 }
5404 if (ImportedBlockDecls.size()) {
5405 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5406 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5407 unsigned IntSize =
5408 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5409 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5410 Context->IntTy, SourceLocation());
5411 InitExprs.push_back(FlagExp);
5412 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005413 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005414 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005415
5416 if (GlobalBlockExpr) {
5417 assert (GlobalConstructionExp == 0 &&
5418 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5419 GlobalConstructionExp = NewRep;
5420 NewRep = DRE;
5421 }
5422
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005423 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5424 Context->getPointerType(NewRep->getType()),
5425 VK_RValue, OK_Ordinary, SourceLocation());
5426 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5427 NewRep);
5428 BlockDeclRefs.clear();
5429 BlockByRefDecls.clear();
5430 BlockByRefDeclsPtrSet.clear();
5431 BlockByCopyDecls.clear();
5432 BlockByCopyDeclsPtrSet.clear();
5433 ImportedBlockDecls.clear();
5434 return NewRep;
5435}
5436
5437bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5438 if (const ObjCForCollectionStmt * CS =
5439 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5440 return CS->getElement() == DS;
5441 return false;
5442}
5443
5444//===----------------------------------------------------------------------===//
5445// Function Body / Expression rewriting
5446//===----------------------------------------------------------------------===//
5447
5448Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5449 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5450 isa<DoStmt>(S) || isa<ForStmt>(S))
5451 Stmts.push_back(S);
5452 else if (isa<ObjCForCollectionStmt>(S)) {
5453 Stmts.push_back(S);
5454 ObjCBcLabelNo.push_back(++BcLabelCount);
5455 }
5456
5457 // Pseudo-object operations and ivar references need special
5458 // treatment because we're going to recursively rewrite them.
5459 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5460 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5461 return RewritePropertyOrImplicitSetter(PseudoOp);
5462 } else {
5463 return RewritePropertyOrImplicitGetter(PseudoOp);
5464 }
5465 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5466 return RewriteObjCIvarRefExpr(IvarRefExpr);
5467 }
5468
5469 SourceRange OrigStmtRange = S->getSourceRange();
5470
5471 // Perform a bottom up rewrite of all children.
5472 for (Stmt::child_range CI = S->children(); CI; ++CI)
5473 if (*CI) {
5474 Stmt *childStmt = (*CI);
5475 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5476 if (newStmt) {
5477 *CI = newStmt;
5478 }
5479 }
5480
5481 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005482 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005483 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5484 InnerContexts.insert(BE->getBlockDecl());
5485 ImportedLocalExternalDecls.clear();
5486 GetInnerBlockDeclRefExprs(BE->getBody(),
5487 InnerBlockDeclRefs, InnerContexts);
5488 // Rewrite the block body in place.
5489 Stmt *SaveCurrentBody = CurrentBody;
5490 CurrentBody = BE->getBody();
5491 PropParentMap = 0;
5492 // block literal on rhs of a property-dot-sytax assignment
5493 // must be replaced by its synthesize ast so getRewrittenText
5494 // works as expected. In this case, what actually ends up on RHS
5495 // is the blockTranscribed which is the helper function for the
5496 // block literal; as in: self.c = ^() {[ace ARR];};
5497 bool saveDisableReplaceStmt = DisableReplaceStmt;
5498 DisableReplaceStmt = false;
5499 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5500 DisableReplaceStmt = saveDisableReplaceStmt;
5501 CurrentBody = SaveCurrentBody;
5502 PropParentMap = 0;
5503 ImportedLocalExternalDecls.clear();
5504 // Now we snarf the rewritten text and stash it away for later use.
5505 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5506 RewrittenBlockExprs[BE] = Str;
5507
5508 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5509
5510 //blockTranscribed->dump();
5511 ReplaceStmt(S, blockTranscribed);
5512 return blockTranscribed;
5513 }
5514 // Handle specific things.
5515 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5516 return RewriteAtEncode(AtEncode);
5517
5518 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5519 return RewriteAtSelector(AtSelector);
5520
5521 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5522 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005523
5524 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5525 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005526
Patrick Beardeb382ec2012-04-19 00:25:12 +00005527 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5528 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005529
5530 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5531 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005532
5533 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5534 dyn_cast<ObjCDictionaryLiteral>(S))
5535 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005536
5537 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5538#if 0
5539 // Before we rewrite it, put the original message expression in a comment.
5540 SourceLocation startLoc = MessExpr->getLocStart();
5541 SourceLocation endLoc = MessExpr->getLocEnd();
5542
5543 const char *startBuf = SM->getCharacterData(startLoc);
5544 const char *endBuf = SM->getCharacterData(endLoc);
5545
5546 std::string messString;
5547 messString += "// ";
5548 messString.append(startBuf, endBuf-startBuf+1);
5549 messString += "\n";
5550
5551 // FIXME: Missing definition of
5552 // InsertText(clang::SourceLocation, char const*, unsigned int).
5553 // InsertText(startLoc, messString.c_str(), messString.size());
5554 // Tried this, but it didn't work either...
5555 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5556#endif
5557 return RewriteMessageExpr(MessExpr);
5558 }
5559
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005560 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5561 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5562 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5563 }
5564
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005565 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5566 return RewriteObjCTryStmt(StmtTry);
5567
5568 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5569 return RewriteObjCSynchronizedStmt(StmtTry);
5570
5571 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5572 return RewriteObjCThrowStmt(StmtThrow);
5573
5574 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5575 return RewriteObjCProtocolExpr(ProtocolExp);
5576
5577 if (ObjCForCollectionStmt *StmtForCollection =
5578 dyn_cast<ObjCForCollectionStmt>(S))
5579 return RewriteObjCForCollectionStmt(StmtForCollection,
5580 OrigStmtRange.getEnd());
5581 if (BreakStmt *StmtBreakStmt =
5582 dyn_cast<BreakStmt>(S))
5583 return RewriteBreakStmt(StmtBreakStmt);
5584 if (ContinueStmt *StmtContinueStmt =
5585 dyn_cast<ContinueStmt>(S))
5586 return RewriteContinueStmt(StmtContinueStmt);
5587
5588 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5589 // and cast exprs.
5590 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5591 // FIXME: What we're doing here is modifying the type-specifier that
5592 // precedes the first Decl. In the future the DeclGroup should have
5593 // a separate type-specifier that we can rewrite.
5594 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5595 // the context of an ObjCForCollectionStmt. For example:
5596 // NSArray *someArray;
5597 // for (id <FooProtocol> index in someArray) ;
5598 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5599 // and it depends on the original text locations/positions.
5600 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5601 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5602
5603 // Blocks rewrite rules.
5604 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5605 DI != DE; ++DI) {
5606 Decl *SD = *DI;
5607 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5608 if (isTopLevelBlockPointerType(ND->getType()))
5609 RewriteBlockPointerDecl(ND);
5610 else if (ND->getType()->isFunctionPointerType())
5611 CheckFunctionPointerDecl(ND->getType(), ND);
5612 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5613 if (VD->hasAttr<BlocksAttr>()) {
5614 static unsigned uniqueByrefDeclCount = 0;
5615 assert(!BlockByRefDeclNo.count(ND) &&
5616 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5617 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005618 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005619 }
5620 else
5621 RewriteTypeOfDecl(VD);
5622 }
5623 }
5624 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5625 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5626 RewriteBlockPointerDecl(TD);
5627 else if (TD->getUnderlyingType()->isFunctionPointerType())
5628 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5629 }
5630 }
5631 }
5632
5633 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5634 RewriteObjCQualifiedInterfaceTypes(CE);
5635
5636 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5637 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5638 assert(!Stmts.empty() && "Statement stack is empty");
5639 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5640 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5641 && "Statement stack mismatch");
5642 Stmts.pop_back();
5643 }
5644 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005645 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5646 ValueDecl *VD = DRE->getDecl();
5647 if (VD->hasAttr<BlocksAttr>())
5648 return RewriteBlockDeclRefExpr(DRE);
5649 if (HasLocalVariableExternalStorage(VD))
5650 return RewriteLocalVariableExternalStorage(DRE);
5651 }
5652
5653 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5654 if (CE->getCallee()->getType()->isBlockPointerType()) {
5655 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5656 ReplaceStmt(S, BlockCall);
5657 return BlockCall;
5658 }
5659 }
5660 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5661 RewriteCastExpr(CE);
5662 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005663 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5664 RewriteImplicitCastObjCExpr(ICE);
5665 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005666#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005667
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005668 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5669 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5670 ICE->getSubExpr(),
5671 SourceLocation());
5672 // Get the new text.
5673 std::string SStr;
5674 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005675 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005676 const std::string &Str = Buf.str();
5677
5678 printf("CAST = %s\n", &Str[0]);
5679 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5680 delete S;
5681 return Replacement;
5682 }
5683#endif
5684 // Return this stmt unmodified.
5685 return S;
5686}
5687
5688void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5689 for (RecordDecl::field_iterator i = RD->field_begin(),
5690 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005691 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005692 if (isTopLevelBlockPointerType(FD->getType()))
5693 RewriteBlockPointerDecl(FD);
5694 if (FD->getType()->isObjCQualifiedIdType() ||
5695 FD->getType()->isObjCQualifiedInterfaceType())
5696 RewriteObjCQualifiedInterfaceTypes(FD);
5697 }
5698}
5699
5700/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5701/// main file of the input.
5702void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5703 switch (D->getKind()) {
5704 case Decl::Function: {
5705 FunctionDecl *FD = cast<FunctionDecl>(D);
5706 if (FD->isOverloadedOperator())
5707 return;
5708
5709 // Since function prototypes don't have ParmDecl's, we check the function
5710 // prototype. This enables us to rewrite function declarations and
5711 // definitions using the same code.
5712 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5713
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005714 if (!FD->isThisDeclarationADefinition())
5715 break;
5716
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005717 // FIXME: If this should support Obj-C++, support CXXTryStmt
5718 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5719 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005720 CurrentBody = Body;
5721 Body =
5722 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5723 FD->setBody(Body);
5724 CurrentBody = 0;
5725 if (PropParentMap) {
5726 delete PropParentMap;
5727 PropParentMap = 0;
5728 }
5729 // This synthesizes and inserts the block "impl" struct, invoke function,
5730 // and any copy/dispose helper functions.
5731 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005732 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005733 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005734 }
5735 break;
5736 }
5737 case Decl::ObjCMethod: {
5738 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5739 if (CompoundStmt *Body = MD->getCompoundBody()) {
5740 CurMethodDef = MD;
5741 CurrentBody = Body;
5742 Body =
5743 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5744 MD->setBody(Body);
5745 CurrentBody = 0;
5746 if (PropParentMap) {
5747 delete PropParentMap;
5748 PropParentMap = 0;
5749 }
5750 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005751 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005752 CurMethodDef = 0;
5753 }
5754 break;
5755 }
5756 case Decl::ObjCImplementation: {
5757 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5758 ClassImplementation.push_back(CI);
5759 break;
5760 }
5761 case Decl::ObjCCategoryImpl: {
5762 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5763 CategoryImplementation.push_back(CI);
5764 break;
5765 }
5766 case Decl::Var: {
5767 VarDecl *VD = cast<VarDecl>(D);
5768 RewriteObjCQualifiedInterfaceTypes(VD);
5769 if (isTopLevelBlockPointerType(VD->getType()))
5770 RewriteBlockPointerDecl(VD);
5771 else if (VD->getType()->isFunctionPointerType()) {
5772 CheckFunctionPointerDecl(VD->getType(), VD);
5773 if (VD->getInit()) {
5774 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5775 RewriteCastExpr(CE);
5776 }
5777 }
5778 } else if (VD->getType()->isRecordType()) {
5779 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5780 if (RD->isCompleteDefinition())
5781 RewriteRecordBody(RD);
5782 }
5783 if (VD->getInit()) {
5784 GlobalVarDecl = VD;
5785 CurrentBody = VD->getInit();
5786 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5787 CurrentBody = 0;
5788 if (PropParentMap) {
5789 delete PropParentMap;
5790 PropParentMap = 0;
5791 }
5792 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5793 GlobalVarDecl = 0;
5794
5795 // This is needed for blocks.
5796 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5797 RewriteCastExpr(CE);
5798 }
5799 }
5800 break;
5801 }
5802 case Decl::TypeAlias:
5803 case Decl::Typedef: {
5804 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5805 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5806 RewriteBlockPointerDecl(TD);
5807 else if (TD->getUnderlyingType()->isFunctionPointerType())
5808 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5809 }
5810 break;
5811 }
5812 case Decl::CXXRecord:
5813 case Decl::Record: {
5814 RecordDecl *RD = cast<RecordDecl>(D);
5815 if (RD->isCompleteDefinition())
5816 RewriteRecordBody(RD);
5817 break;
5818 }
5819 default:
5820 break;
5821 }
5822 // Nothing yet.
5823}
5824
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005825/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5826/// protocol reference symbols in the for of:
5827/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5828static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5829 ObjCProtocolDecl *PDecl,
5830 std::string &Result) {
5831 // Also output .objc_protorefs$B section and its meta-data.
5832 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005833 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005834 Result += "struct _protocol_t *";
5835 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5836 Result += PDecl->getNameAsString();
5837 Result += " = &";
5838 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5839 Result += ";\n";
5840}
5841
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005842void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5843 if (Diags.hasErrorOccurred())
5844 return;
5845
5846 RewriteInclude();
5847
5848 // Here's a great place to add any extra declarations that may be needed.
5849 // Write out meta data for each @protocol(<expr>).
5850 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005851 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005852 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005853 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5854 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005855
5856 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005857
5858 if (ClassImplementation.size() || CategoryImplementation.size())
5859 RewriteImplementations();
5860
Fariborz Jahanian57317782012-02-21 23:58:41 +00005861 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5862 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5863 // Write struct declaration for the class matching its ivar declarations.
5864 // Note that for modern abi, this is postponed until the end of TU
5865 // because class extensions and the implementation might declare their own
5866 // private ivars.
5867 RewriteInterfaceDecl(CDecl);
5868 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005869
5870 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5871 // we are done.
5872 if (const RewriteBuffer *RewriteBuf =
5873 Rewrite.getRewriteBufferFor(MainFileID)) {
5874 //printf("Changed:\n");
5875 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5876 } else {
5877 llvm::errs() << "No changes\n";
5878 }
5879
5880 if (ClassImplementation.size() || CategoryImplementation.size() ||
5881 ProtocolExprDecls.size()) {
5882 // Rewrite Objective-c meta data*
5883 std::string ResultStr;
5884 RewriteMetaDataIntoBuffer(ResultStr);
5885 // Emit metadata.
5886 *OutFile << ResultStr;
5887 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005888 // Emit ImageInfo;
5889 {
5890 std::string ResultStr;
5891 WriteImageInfo(ResultStr);
5892 *OutFile << ResultStr;
5893 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005894 OutFile->flush();
5895}
5896
5897void RewriteModernObjC::Initialize(ASTContext &context) {
5898 InitializeCommon(context);
5899
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005900 Preamble += "#ifndef __OBJC2__\n";
5901 Preamble += "#define __OBJC2__\n";
5902 Preamble += "#endif\n";
5903
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005904 // declaring objc_selector outside the parameter list removes a silly
5905 // scope related warning...
5906 if (IsHeader)
5907 Preamble = "#pragma once\n";
5908 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005909 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5910 Preamble += "\n\tstruct objc_object *superClass; ";
5911 // Add a constructor for creating temporary objects.
5912 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5913 Preamble += ": object(o), superClass(s) {} ";
5914 Preamble += "\n};\n";
5915
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005916 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005917 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005918 // These are currently generated.
5919 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005920 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005921 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005922 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5923 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005924 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005925 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005926 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5927 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005928 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005929
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005930 // These need be generated for performance. Currently they are not,
5931 // using API calls instead.
5932 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5933 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5934 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5935
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005936 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005937 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5938 Preamble += "typedef struct objc_object Protocol;\n";
5939 Preamble += "#define _REWRITER_typedef_Protocol\n";
5940 Preamble += "#endif\n";
5941 if (LangOpts.MicrosoftExt) {
5942 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5943 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005944 }
5945 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005946 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005947
5948 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5949 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5950 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5951 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5952 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5953
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005954 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005955 Preamble += "(const char *);\n";
5956 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5957 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005958 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005959 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005960 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005961 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005962 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5963 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005964 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5965 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5966 Preamble += "struct __objcFastEnumerationState {\n\t";
5967 Preamble += "unsigned long state;\n\t";
5968 Preamble += "void **itemsPtr;\n\t";
5969 Preamble += "unsigned long *mutationsPtr;\n\t";
5970 Preamble += "unsigned long extra[5];\n};\n";
5971 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5972 Preamble += "#define __FASTENUMERATIONSTATE\n";
5973 Preamble += "#endif\n";
5974 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5975 Preamble += "struct __NSConstantStringImpl {\n";
5976 Preamble += " int *isa;\n";
5977 Preamble += " int flags;\n";
5978 Preamble += " char *str;\n";
5979 Preamble += " long length;\n";
5980 Preamble += "};\n";
5981 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5982 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5983 Preamble += "#else\n";
5984 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5985 Preamble += "#endif\n";
5986 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5987 Preamble += "#endif\n";
5988 // Blocks preamble.
5989 Preamble += "#ifndef BLOCK_IMPL\n";
5990 Preamble += "#define BLOCK_IMPL\n";
5991 Preamble += "struct __block_impl {\n";
5992 Preamble += " void *isa;\n";
5993 Preamble += " int Flags;\n";
5994 Preamble += " int Reserved;\n";
5995 Preamble += " void *FuncPtr;\n";
5996 Preamble += "};\n";
5997 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5998 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5999 Preamble += "extern \"C\" __declspec(dllexport) "
6000 "void _Block_object_assign(void *, const void *, const int);\n";
6001 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6002 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6003 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6004 Preamble += "#else\n";
6005 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6006 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6007 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6008 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6009 Preamble += "#endif\n";
6010 Preamble += "#endif\n";
6011 if (LangOpts.MicrosoftExt) {
6012 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6013 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6014 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6015 Preamble += "#define __attribute__(X)\n";
6016 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006017 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006018 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006019 Preamble += "#endif\n";
6020 Preamble += "#ifndef __block\n";
6021 Preamble += "#define __block\n";
6022 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006023 }
6024 else {
6025 Preamble += "#define __block\n";
6026 Preamble += "#define __weak\n";
6027 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006028
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006029 // Declarations required for modern objective-c array and dictionary literals.
6030 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006031 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006032 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006033 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006034 Preamble += "\tva_list marker;\n";
6035 Preamble += "\tva_start(marker, count);\n";
6036 Preamble += "\tarr = new void *[count];\n";
6037 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6038 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6039 Preamble += "\tva_end( marker );\n";
6040 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006041 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006042 Preamble += "\tdelete[] arr;\n";
6043 Preamble += " }\n";
6044 Preamble += "};\n";
6045
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006046 // Declaration required for implementation of @autoreleasepool statement.
6047 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6048 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6049 Preamble += "struct __AtAutoreleasePool {\n";
6050 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6051 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6052 Preamble += " void * atautoreleasepoolobj;\n";
6053 Preamble += "};\n";
6054
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006055 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6056 // as this avoids warning in any 64bit/32bit compilation model.
6057 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6058}
6059
6060/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6061/// ivar offset.
6062void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6063 std::string &Result) {
6064 if (ivar->isBitField()) {
6065 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6066 // place all bitfields at offset 0.
6067 Result += "0";
6068 } else {
6069 Result += "__OFFSETOFIVAR__(struct ";
6070 Result += ivar->getContainingInterface()->getNameAsString();
6071 if (LangOpts.MicrosoftExt)
6072 Result += "_IMPL";
6073 Result += ", ";
6074 Result += ivar->getNameAsString();
6075 Result += ")";
6076 }
6077}
6078
6079/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6080/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006081/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006082/// char *attributes;
6083/// }
6084
6085/// struct _prop_list_t {
6086/// uint32_t entsize; // sizeof(struct _prop_t)
6087/// uint32_t count_of_properties;
6088/// struct _prop_t prop_list[count_of_properties];
6089/// }
6090
6091/// struct _protocol_t;
6092
6093/// struct _protocol_list_t {
6094/// long protocol_count; // Note, this is 32/64 bit
6095/// struct _protocol_t * protocol_list[protocol_count];
6096/// }
6097
6098/// struct _objc_method {
6099/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006100/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006101/// char *_imp;
6102/// }
6103
6104/// struct _method_list_t {
6105/// uint32_t entsize; // sizeof(struct _objc_method)
6106/// uint32_t method_count;
6107/// struct _objc_method method_list[method_count];
6108/// }
6109
6110/// struct _protocol_t {
6111/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006112/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006113/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006114/// const struct method_list_t *instance_methods;
6115/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006116/// const struct method_list_t *optionalInstanceMethods;
6117/// const struct method_list_t *optionalClassMethods;
6118/// const struct _prop_list_t * properties;
6119/// const uint32_t size; // sizeof(struct _protocol_t)
6120/// const uint32_t flags; // = 0
6121/// const char ** extendedMethodTypes;
6122/// }
6123
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006124/// struct _ivar_t {
6125/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006126/// const char *name;
6127/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006128/// uint32_t alignment;
6129/// uint32_t size;
6130/// }
6131
6132/// struct _ivar_list_t {
6133/// uint32 entsize; // sizeof(struct _ivar_t)
6134/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006135/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006136/// }
6137
6138/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006139/// uint32_t flags;
6140/// uint32_t instanceStart;
6141/// uint32_t instanceSize;
6142/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006143/// const uint8_t *ivarLayout;
6144/// const char *name;
6145/// const struct _method_list_t *baseMethods;
6146/// const struct _protocol_list_t *baseProtocols;
6147/// const struct _ivar_list_t *ivars;
6148/// const uint8_t *weakIvarLayout;
6149/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006150/// }
6151
6152/// struct _class_t {
6153/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006154/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006155/// void *cache;
6156/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006157/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006158/// }
6159
6160/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006161/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006162/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006163/// const struct _method_list_t *instance_methods;
6164/// const struct _method_list_t *class_methods;
6165/// const struct _protocol_list_t *protocols;
6166/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006167/// }
6168
6169/// MessageRefTy - LLVM for:
6170/// struct _message_ref_t {
6171/// IMP messenger;
6172/// SEL name;
6173/// };
6174
6175/// SuperMessageRefTy - LLVM for:
6176/// struct _super_message_ref_t {
6177/// SUPER_IMP messenger;
6178/// SEL name;
6179/// };
6180
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006181static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006182 static bool meta_data_declared = false;
6183 if (meta_data_declared)
6184 return;
6185
6186 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006187 Result += "\tconst char *name;\n";
6188 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006189 Result += "};\n";
6190
6191 Result += "\nstruct _protocol_t;\n";
6192
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006193 Result += "\nstruct _objc_method {\n";
6194 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006195 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006196 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006197 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006198
6199 Result += "\nstruct _protocol_t {\n";
6200 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006201 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006202 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006203 Result += "\tconst struct method_list_t *instance_methods;\n";
6204 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006205 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6206 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6207 Result += "\tconst struct _prop_list_t * properties;\n";
6208 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6209 Result += "\tconst unsigned int flags; // = 0\n";
6210 Result += "\tconst char ** extendedMethodTypes;\n";
6211 Result += "};\n";
6212
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006213 Result += "\nstruct _ivar_t {\n";
6214 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006215 Result += "\tconst char *name;\n";
6216 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006217 Result += "\tunsigned int alignment;\n";
6218 Result += "\tunsigned int size;\n";
6219 Result += "};\n";
6220
6221 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006222 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006223 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006224 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006225 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6226 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006227 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006228 Result += "\tconst unsigned char *ivarLayout;\n";
6229 Result += "\tconst char *name;\n";
6230 Result += "\tconst struct _method_list_t *baseMethods;\n";
6231 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6232 Result += "\tconst struct _ivar_list_t *ivars;\n";
6233 Result += "\tconst unsigned char *weakIvarLayout;\n";
6234 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006235 Result += "};\n";
6236
6237 Result += "\nstruct _class_t {\n";
6238 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006239 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006240 Result += "\tvoid *cache;\n";
6241 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006242 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006243 Result += "};\n";
6244
6245 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006246 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006247 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006248 Result += "\tconst struct _method_list_t *instance_methods;\n";
6249 Result += "\tconst struct _method_list_t *class_methods;\n";
6250 Result += "\tconst struct _protocol_list_t *protocols;\n";
6251 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006252 Result += "};\n";
6253
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006254 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006255 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006256 meta_data_declared = true;
6257}
6258
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006259static void Write_protocol_list_t_TypeDecl(std::string &Result,
6260 long super_protocol_count) {
6261 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6262 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6263 Result += "\tstruct _protocol_t *super_protocols[";
6264 Result += utostr(super_protocol_count); Result += "];\n";
6265 Result += "}";
6266}
6267
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006268static void Write_method_list_t_TypeDecl(std::string &Result,
6269 unsigned int method_count) {
6270 Result += "struct /*_method_list_t*/"; Result += " {\n";
6271 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6272 Result += "\tunsigned int method_count;\n";
6273 Result += "\tstruct _objc_method method_list[";
6274 Result += utostr(method_count); Result += "];\n";
6275 Result += "}";
6276}
6277
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006278static void Write__prop_list_t_TypeDecl(std::string &Result,
6279 unsigned int property_count) {
6280 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6281 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6282 Result += "\tunsigned int count_of_properties;\n";
6283 Result += "\tstruct _prop_t prop_list[";
6284 Result += utostr(property_count); Result += "];\n";
6285 Result += "}";
6286}
6287
Fariborz Jahanianae932952012-02-10 20:47:10 +00006288static void Write__ivar_list_t_TypeDecl(std::string &Result,
6289 unsigned int ivar_count) {
6290 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6291 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6292 Result += "\tunsigned int count;\n";
6293 Result += "\tstruct _ivar_t ivar_list[";
6294 Result += utostr(ivar_count); Result += "];\n";
6295 Result += "}";
6296}
6297
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006298static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6299 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6300 StringRef VarName,
6301 StringRef ProtocolName) {
6302 if (SuperProtocols.size() > 0) {
6303 Result += "\nstatic ";
6304 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6305 Result += " "; Result += VarName;
6306 Result += ProtocolName;
6307 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6308 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6309 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6310 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6311 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6312 Result += SuperPD->getNameAsString();
6313 if (i == e-1)
6314 Result += "\n};\n";
6315 else
6316 Result += ",\n";
6317 }
6318 }
6319}
6320
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006321static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6322 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006323 ArrayRef<ObjCMethodDecl *> Methods,
6324 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006325 StringRef TopLevelDeclName,
6326 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006327 if (Methods.size() > 0) {
6328 Result += "\nstatic ";
6329 Write_method_list_t_TypeDecl(Result, Methods.size());
6330 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006331 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006332 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6333 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6334 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6335 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6336 ObjCMethodDecl *MD = Methods[i];
6337 if (i == 0)
6338 Result += "\t{{(struct objc_selector *)\"";
6339 else
6340 Result += "\t{(struct objc_selector *)\"";
6341 Result += (MD)->getSelector().getAsString(); Result += "\"";
6342 Result += ", ";
6343 std::string MethodTypeString;
6344 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6345 Result += "\""; Result += MethodTypeString; Result += "\"";
6346 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006347 if (!MethodImpl)
6348 Result += "0";
6349 else {
6350 Result += "(void *)";
6351 Result += RewriteObj.MethodInternalNames[MD];
6352 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006353 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006354 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006355 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006356 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006357 }
6358 Result += "};\n";
6359 }
6360}
6361
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006362static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006363 ASTContext *Context, std::string &Result,
6364 ArrayRef<ObjCPropertyDecl *> Properties,
6365 const Decl *Container,
6366 StringRef VarName,
6367 StringRef ProtocolName) {
6368 if (Properties.size() > 0) {
6369 Result += "\nstatic ";
6370 Write__prop_list_t_TypeDecl(Result, Properties.size());
6371 Result += " "; Result += VarName;
6372 Result += ProtocolName;
6373 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6374 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6375 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6376 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6377 ObjCPropertyDecl *PropDecl = Properties[i];
6378 if (i == 0)
6379 Result += "\t{{\"";
6380 else
6381 Result += "\t{\"";
6382 Result += PropDecl->getName(); Result += "\",";
6383 std::string PropertyTypeString, QuotePropertyTypeString;
6384 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6385 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6386 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6387 if (i == e-1)
6388 Result += "}}\n";
6389 else
6390 Result += "},\n";
6391 }
6392 Result += "};\n";
6393 }
6394}
6395
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006396// Metadata flags
6397enum MetaDataDlags {
6398 CLS = 0x0,
6399 CLS_META = 0x1,
6400 CLS_ROOT = 0x2,
6401 OBJC2_CLS_HIDDEN = 0x10,
6402 CLS_EXCEPTION = 0x20,
6403
6404 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6405 CLS_HAS_IVAR_RELEASER = 0x40,
6406 /// class was compiled with -fobjc-arr
6407 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6408};
6409
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006410static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6411 unsigned int flags,
6412 const std::string &InstanceStart,
6413 const std::string &InstanceSize,
6414 ArrayRef<ObjCMethodDecl *>baseMethods,
6415 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6416 ArrayRef<ObjCIvarDecl *>ivars,
6417 ArrayRef<ObjCPropertyDecl *>Properties,
6418 StringRef VarName,
6419 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006420 Result += "\nstatic struct _class_ro_t ";
6421 Result += VarName; Result += ClassName;
6422 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6423 Result += "\t";
6424 Result += llvm::utostr(flags); Result += ", ";
6425 Result += InstanceStart; Result += ", ";
6426 Result += InstanceSize; Result += ", \n";
6427 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006428 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6429 if (Triple.getArch() == llvm::Triple::x86_64)
6430 // uint32_t const reserved; // only when building for 64bit targets
6431 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006432 // const uint8_t * const ivarLayout;
6433 Result += "0, \n\t";
6434 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006435 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006436 if (baseMethods.size() > 0) {
6437 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006438 if (metaclass)
6439 Result += "_OBJC_$_CLASS_METHODS_";
6440 else
6441 Result += "_OBJC_$_INSTANCE_METHODS_";
6442 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006443 Result += ",\n\t";
6444 }
6445 else
6446 Result += "0, \n\t";
6447
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006448 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006449 Result += "(const struct _objc_protocol_list *)&";
6450 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6451 Result += ",\n\t";
6452 }
6453 else
6454 Result += "0, \n\t";
6455
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006456 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006457 Result += "(const struct _ivar_list_t *)&";
6458 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6459 Result += ",\n\t";
6460 }
6461 else
6462 Result += "0, \n\t";
6463
6464 // weakIvarLayout
6465 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006466 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006467 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006468 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006469 Result += ",\n";
6470 }
6471 else
6472 Result += "0, \n";
6473
6474 Result += "};\n";
6475}
6476
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006477static void Write_class_t(ASTContext *Context, std::string &Result,
6478 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006479 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6480 bool rootClass = (!CDecl->getSuperClass());
6481 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006482
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006483 if (!rootClass) {
6484 // Find the Root class
6485 RootClass = CDecl->getSuperClass();
6486 while (RootClass->getSuperClass()) {
6487 RootClass = RootClass->getSuperClass();
6488 }
6489 }
6490
6491 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006492 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006493 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006494 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006495 if (CDecl->getImplementation())
6496 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006497 else
6498 Result += "__declspec(dllimport) ";
6499
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006500 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006501 Result += CDecl->getNameAsString();
6502 Result += ";\n";
6503 }
6504 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006505 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006506 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006507 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006508 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006509 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006510 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006511 else
6512 Result += "__declspec(dllimport) ";
6513
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006514 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006515 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006516 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006517 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006518
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006519 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006520 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006521 if (RootClass->getImplementation())
6522 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006523 else
6524 Result += "__declspec(dllimport) ";
6525
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006526 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006527 Result += VarName;
6528 Result += RootClass->getNameAsString();
6529 Result += ";\n";
6530 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006531 }
6532
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006533 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6534 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006535 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6536 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006537 if (metaclass) {
6538 if (!rootClass) {
6539 Result += "0, // &"; Result += VarName;
6540 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006541 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006542 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006543 Result += CDecl->getSuperClass()->getNameAsString();
6544 Result += ",\n\t";
6545 }
6546 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006547 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006548 Result += CDecl->getNameAsString();
6549 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006550 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006551 Result += ",\n\t";
6552 }
6553 }
6554 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006555 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006556 Result += CDecl->getNameAsString();
6557 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006558 if (!rootClass) {
6559 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006560 Result += CDecl->getSuperClass()->getNameAsString();
6561 Result += ",\n\t";
6562 }
6563 else
6564 Result += "0,\n\t";
6565 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006566 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6567 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6568 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006569 Result += "&_OBJC_METACLASS_RO_$_";
6570 else
6571 Result += "&_OBJC_CLASS_RO_$_";
6572 Result += CDecl->getNameAsString();
6573 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006574
6575 // Add static function to initialize some of the meta-data fields.
6576 // avoid doing it twice.
6577 if (metaclass)
6578 return;
6579
6580 const ObjCInterfaceDecl *SuperClass =
6581 rootClass ? CDecl : CDecl->getSuperClass();
6582
6583 Result += "static void OBJC_CLASS_SETUP_$_";
6584 Result += CDecl->getNameAsString();
6585 Result += "(void ) {\n";
6586 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6587 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006588 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006589
6590 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006591 Result += ".superclass = ";
6592 if (rootClass)
6593 Result += "&OBJC_CLASS_$_";
6594 else
6595 Result += "&OBJC_METACLASS_$_";
6596
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006597 Result += SuperClass->getNameAsString(); Result += ";\n";
6598
6599 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6600 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6601
6602 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6603 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6604 Result += CDecl->getNameAsString(); Result += ";\n";
6605
6606 if (!rootClass) {
6607 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6608 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6609 Result += SuperClass->getNameAsString(); Result += ";\n";
6610 }
6611
6612 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6613 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6614 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006615}
6616
Fariborz Jahanian61186122012-02-17 18:40:41 +00006617static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6618 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006619 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006620 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006621 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6622 ArrayRef<ObjCMethodDecl *> ClassMethods,
6623 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6624 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006625 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006626 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006627 // must declare an extern class object in case this class is not implemented
6628 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006629 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006630 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006631 if (ClassDecl->getImplementation())
6632 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006633 else
6634 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006635
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006636 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006637 Result += "OBJC_CLASS_$_"; Result += ClassName;
6638 Result += ";\n";
6639
Fariborz Jahanian61186122012-02-17 18:40:41 +00006640 Result += "\nstatic struct _category_t ";
6641 Result += "_OBJC_$_CATEGORY_";
6642 Result += ClassName; Result += "_$_"; Result += CatName;
6643 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6644 Result += "{\n";
6645 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006646 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006647 Result += ",\n";
6648 if (InstanceMethods.size() > 0) {
6649 Result += "\t(const struct _method_list_t *)&";
6650 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6651 Result += ClassName; Result += "_$_"; Result += CatName;
6652 Result += ",\n";
6653 }
6654 else
6655 Result += "\t0,\n";
6656
6657 if (ClassMethods.size() > 0) {
6658 Result += "\t(const struct _method_list_t *)&";
6659 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6660 Result += ClassName; Result += "_$_"; Result += CatName;
6661 Result += ",\n";
6662 }
6663 else
6664 Result += "\t0,\n";
6665
6666 if (RefedProtocols.size() > 0) {
6667 Result += "\t(const struct _protocol_list_t *)&";
6668 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6669 Result += ClassName; Result += "_$_"; Result += CatName;
6670 Result += ",\n";
6671 }
6672 else
6673 Result += "\t0,\n";
6674
6675 if (ClassProperties.size() > 0) {
6676 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6677 Result += ClassName; Result += "_$_"; Result += CatName;
6678 Result += ",\n";
6679 }
6680 else
6681 Result += "\t0,\n";
6682
6683 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006684
6685 // Add static function to initialize the class pointer in the category structure.
6686 Result += "static void OBJC_CATEGORY_SETUP_$_";
6687 Result += ClassDecl->getNameAsString();
6688 Result += "_$_";
6689 Result += CatName;
6690 Result += "(void ) {\n";
6691 Result += "\t_OBJC_$_CATEGORY_";
6692 Result += ClassDecl->getNameAsString();
6693 Result += "_$_";
6694 Result += CatName;
6695 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6696 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006697}
6698
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006699static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6700 ASTContext *Context, std::string &Result,
6701 ArrayRef<ObjCMethodDecl *> Methods,
6702 StringRef VarName,
6703 StringRef ProtocolName) {
6704 if (Methods.size() == 0)
6705 return;
6706
6707 Result += "\nstatic const char *";
6708 Result += VarName; Result += ProtocolName;
6709 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6710 Result += "{\n";
6711 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6712 ObjCMethodDecl *MD = Methods[i];
6713 std::string MethodTypeString, QuoteMethodTypeString;
6714 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6715 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6716 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6717 if (i == e-1)
6718 Result += "\n};\n";
6719 else {
6720 Result += ",\n";
6721 }
6722 }
6723}
6724
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006725static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6726 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006727 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006728 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006729 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006730 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6731 // this is what happens:
6732 /**
6733 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6734 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6735 Class->getVisibility() == HiddenVisibility)
6736 Visibility shoud be: HiddenVisibility;
6737 else
6738 Visibility shoud be: DefaultVisibility;
6739 */
6740
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006741 Result += "\n";
6742 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6743 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006744 if (Context->getLangOpts().MicrosoftExt)
6745 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6746
6747 if (!Context->getLangOpts().MicrosoftExt ||
6748 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006749 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006750 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006751 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006752 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006753 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006754 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6755 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006756 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6757 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006758 }
6759}
6760
Fariborz Jahanianae932952012-02-10 20:47:10 +00006761static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6762 ASTContext *Context, std::string &Result,
6763 ArrayRef<ObjCIvarDecl *> Ivars,
6764 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006765 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006766 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006767 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006768
Fariborz Jahanianae932952012-02-10 20:47:10 +00006769 Result += "\nstatic ";
6770 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6771 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006772 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006773 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6774 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6775 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6776 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6777 ObjCIvarDecl *IvarDecl = Ivars[i];
6778 if (i == 0)
6779 Result += "\t{{";
6780 else
6781 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006782 Result += "(unsigned long int *)&";
6783 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006784 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006785
6786 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6787 std::string IvarTypeString, QuoteIvarTypeString;
6788 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6789 IvarDecl);
6790 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6791 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6792
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006793 // FIXME. this alignment represents the host alignment and need be changed to
6794 // represent the target alignment.
6795 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6796 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006797 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006798 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6799 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006800 if (i == e-1)
6801 Result += "}}\n";
6802 else
6803 Result += "},\n";
6804 }
6805 Result += "};\n";
6806 }
6807}
6808
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006809/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006810void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6811 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006812
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006813 // Do not synthesize the protocol more than once.
6814 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6815 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006816 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006817
6818 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6819 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006820 // Must write out all protocol definitions in current qualifier list,
6821 // and in their nested qualifiers before writing out current definition.
6822 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6823 E = PDecl->protocol_end(); I != E; ++I)
6824 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006825
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006826 // Construct method lists.
6827 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6828 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6829 for (ObjCProtocolDecl::instmeth_iterator
6830 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6831 I != E; ++I) {
6832 ObjCMethodDecl *MD = *I;
6833 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6834 OptInstanceMethods.push_back(MD);
6835 } else {
6836 InstanceMethods.push_back(MD);
6837 }
6838 }
6839
6840 for (ObjCProtocolDecl::classmeth_iterator
6841 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6842 I != E; ++I) {
6843 ObjCMethodDecl *MD = *I;
6844 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6845 OptClassMethods.push_back(MD);
6846 } else {
6847 ClassMethods.push_back(MD);
6848 }
6849 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006850 std::vector<ObjCMethodDecl *> AllMethods;
6851 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6852 AllMethods.push_back(InstanceMethods[i]);
6853 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6854 AllMethods.push_back(ClassMethods[i]);
6855 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6856 AllMethods.push_back(OptInstanceMethods[i]);
6857 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6858 AllMethods.push_back(OptClassMethods[i]);
6859
6860 Write__extendedMethodTypes_initializer(*this, Context, Result,
6861 AllMethods,
6862 "_OBJC_PROTOCOL_METHOD_TYPES_",
6863 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006864 // Protocol's super protocol list
6865 std::vector<ObjCProtocolDecl *> SuperProtocols;
6866 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6867 E = PDecl->protocol_end(); I != E; ++I)
6868 SuperProtocols.push_back(*I);
6869
6870 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6871 "_OBJC_PROTOCOL_REFS_",
6872 PDecl->getNameAsString());
6873
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006874 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006875 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006876 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006877
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006878 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006879 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006880 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006881
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006882 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006883 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006884 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006885
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006886 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006887 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006888 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006889
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006890 // Protocol's property metadata.
6891 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6892 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6893 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00006894 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006895
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006896 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006897 /* Container */0,
6898 "_OBJC_PROTOCOL_PROPERTIES_",
6899 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006900
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006901 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006902 Result += "\n";
6903 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006904 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006905 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006906 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006907 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6908 Result += "\t0,\n"; // id is; is null
6909 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006910 if (SuperProtocols.size() > 0) {
6911 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6912 Result += PDecl->getNameAsString(); Result += ",\n";
6913 }
6914 else
6915 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006916 if (InstanceMethods.size() > 0) {
6917 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6918 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006919 }
6920 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006921 Result += "\t0,\n";
6922
6923 if (ClassMethods.size() > 0) {
6924 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6925 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006926 }
6927 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006928 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006929
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006930 if (OptInstanceMethods.size() > 0) {
6931 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6932 Result += PDecl->getNameAsString(); Result += ",\n";
6933 }
6934 else
6935 Result += "\t0,\n";
6936
6937 if (OptClassMethods.size() > 0) {
6938 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6939 Result += PDecl->getNameAsString(); Result += ",\n";
6940 }
6941 else
6942 Result += "\t0,\n";
6943
6944 if (ProtocolProperties.size() > 0) {
6945 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6946 Result += PDecl->getNameAsString(); Result += ",\n";
6947 }
6948 else
6949 Result += "\t0,\n";
6950
6951 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6952 Result += "\t0,\n";
6953
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006954 if (AllMethods.size() > 0) {
6955 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6956 Result += PDecl->getNameAsString();
6957 Result += "\n};\n";
6958 }
6959 else
6960 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006961
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006962 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006963 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006964 Result += "struct _protocol_t *";
6965 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6966 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6967 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006968
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006969 // Mark this protocol as having been generated.
6970 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6971 llvm_unreachable("protocol already synthesized");
6972
6973}
6974
6975void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6976 const ObjCList<ObjCProtocolDecl> &Protocols,
6977 StringRef prefix, StringRef ClassName,
6978 std::string &Result) {
6979 if (Protocols.empty()) return;
6980
6981 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006982 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006983
6984 // Output the top lovel protocol meta-data for the class.
6985 /* struct _objc_protocol_list {
6986 struct _objc_protocol_list *next;
6987 int protocol_count;
6988 struct _objc_protocol *class_protocols[];
6989 }
6990 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006991 Result += "\n";
6992 if (LangOpts.MicrosoftExt)
6993 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6994 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006995 Result += "\tstruct _objc_protocol_list *next;\n";
6996 Result += "\tint protocol_count;\n";
6997 Result += "\tstruct _objc_protocol *class_protocols[";
6998 Result += utostr(Protocols.size());
6999 Result += "];\n} _OBJC_";
7000 Result += prefix;
7001 Result += "_PROTOCOLS_";
7002 Result += ClassName;
7003 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7004 "{\n\t0, ";
7005 Result += utostr(Protocols.size());
7006 Result += "\n";
7007
7008 Result += "\t,{&_OBJC_PROTOCOL_";
7009 Result += Protocols[0]->getNameAsString();
7010 Result += " \n";
7011
7012 for (unsigned i = 1; i != Protocols.size(); i++) {
7013 Result += "\t ,&_OBJC_PROTOCOL_";
7014 Result += Protocols[i]->getNameAsString();
7015 Result += "\n";
7016 }
7017 Result += "\t }\n};\n";
7018}
7019
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007020/// hasObjCExceptionAttribute - Return true if this class or any super
7021/// class has the __objc_exception__ attribute.
7022/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7023static bool hasObjCExceptionAttribute(ASTContext &Context,
7024 const ObjCInterfaceDecl *OID) {
7025 if (OID->hasAttr<ObjCExceptionAttr>())
7026 return true;
7027 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7028 return hasObjCExceptionAttribute(Context, Super);
7029 return false;
7030}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007031
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007032void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7033 std::string &Result) {
7034 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7035
7036 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007037 if (CDecl->isImplicitInterfaceDecl())
7038 assert(false &&
7039 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007040
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007041 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007042 SmallVector<ObjCIvarDecl *, 8> IVars;
7043
7044 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7045 IVD; IVD = IVD->getNextIvar()) {
7046 // Ignore unnamed bit-fields.
7047 if (!IVD->getDeclName())
7048 continue;
7049 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007050 }
7051
Fariborz Jahanianae932952012-02-10 20:47:10 +00007052 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007053 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007054 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007055
7056 // Build _objc_method_list for class's instance methods if needed
7057 SmallVector<ObjCMethodDecl *, 32>
7058 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7059
7060 // If any of our property implementations have associated getters or
7061 // setters, produce metadata for them as well.
7062 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7063 PropEnd = IDecl->propimpl_end();
7064 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007065 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007066 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007067 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007068 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007069 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007070 if (!PD)
7071 continue;
7072 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007073 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007074 InstanceMethods.push_back(Getter);
7075 if (PD->isReadOnly())
7076 continue;
7077 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007078 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007079 InstanceMethods.push_back(Setter);
7080 }
7081
7082 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7083 "_OBJC_$_INSTANCE_METHODS_",
7084 IDecl->getNameAsString(), true);
7085
7086 SmallVector<ObjCMethodDecl *, 32>
7087 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7088
7089 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7090 "_OBJC_$_CLASS_METHODS_",
7091 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007092
7093 // Protocols referenced in class declaration?
7094 // Protocol's super protocol list
7095 std::vector<ObjCProtocolDecl *> RefedProtocols;
7096 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7097 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7098 E = Protocols.end();
7099 I != E; ++I) {
7100 RefedProtocols.push_back(*I);
7101 // Must write out all protocol definitions in current qualifier list,
7102 // and in their nested qualifiers before writing out current definition.
7103 RewriteObjCProtocolMetaData(*I, Result);
7104 }
7105
7106 Write_protocol_list_initializer(Context, Result,
7107 RefedProtocols,
7108 "_OBJC_CLASS_PROTOCOLS_$_",
7109 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007110
7111 // Protocol's property metadata.
7112 std::vector<ObjCPropertyDecl *> ClassProperties;
7113 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7114 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007115 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007116
7117 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007118 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007119 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007120 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007121
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007122
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007123 // Data for initializing _class_ro_t metaclass meta-data
7124 uint32_t flags = CLS_META;
7125 std::string InstanceSize;
7126 std::string InstanceStart;
7127
7128
7129 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7130 if (classIsHidden)
7131 flags |= OBJC2_CLS_HIDDEN;
7132
7133 if (!CDecl->getSuperClass())
7134 // class is root
7135 flags |= CLS_ROOT;
7136 InstanceSize = "sizeof(struct _class_t)";
7137 InstanceStart = InstanceSize;
7138 Write__class_ro_t_initializer(Context, Result, flags,
7139 InstanceStart, InstanceSize,
7140 ClassMethods,
7141 0,
7142 0,
7143 0,
7144 "_OBJC_METACLASS_RO_$_",
7145 CDecl->getNameAsString());
7146
7147
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007148 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007149 flags = CLS;
7150 if (classIsHidden)
7151 flags |= OBJC2_CLS_HIDDEN;
7152
7153 if (hasObjCExceptionAttribute(*Context, CDecl))
7154 flags |= CLS_EXCEPTION;
7155
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007156 if (!CDecl->getSuperClass())
7157 // class is root
7158 flags |= CLS_ROOT;
7159
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007160 InstanceSize.clear();
7161 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007162 if (!ObjCSynthesizedStructs.count(CDecl)) {
7163 InstanceSize = "0";
7164 InstanceStart = "0";
7165 }
7166 else {
7167 InstanceSize = "sizeof(struct ";
7168 InstanceSize += CDecl->getNameAsString();
7169 InstanceSize += "_IMPL)";
7170
7171 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7172 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007173 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007174 }
7175 else
7176 InstanceStart = InstanceSize;
7177 }
7178 Write__class_ro_t_initializer(Context, Result, flags,
7179 InstanceStart, InstanceSize,
7180 InstanceMethods,
7181 RefedProtocols,
7182 IVars,
7183 ClassProperties,
7184 "_OBJC_CLASS_RO_$_",
7185 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007186
7187 Write_class_t(Context, Result,
7188 "OBJC_METACLASS_$_",
7189 CDecl, /*metaclass*/true);
7190
7191 Write_class_t(Context, Result,
7192 "OBJC_CLASS_$_",
7193 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007194
7195 if (ImplementationIsNonLazy(IDecl))
7196 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007197
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007198}
7199
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007200void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7201 int ClsDefCount = ClassImplementation.size();
7202 if (!ClsDefCount)
7203 return;
7204 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7205 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7206 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7207 for (int i = 0; i < ClsDefCount; i++) {
7208 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7209 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7210 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7211 Result += CDecl->getName(); Result += ",\n";
7212 }
7213 Result += "};\n";
7214}
7215
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007216void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7217 int ClsDefCount = ClassImplementation.size();
7218 int CatDefCount = CategoryImplementation.size();
7219
7220 // For each implemented class, write out all its meta data.
7221 for (int i = 0; i < ClsDefCount; i++)
7222 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7223
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007224 RewriteClassSetupInitHook(Result);
7225
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007226 // For each implemented category, write out all its meta data.
7227 for (int i = 0; i < CatDefCount; i++)
7228 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7229
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007230 RewriteCategorySetupInitHook(Result);
7231
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007232 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007233 if (LangOpts.MicrosoftExt)
7234 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007235 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7236 Result += llvm::utostr(ClsDefCount); Result += "]";
7237 Result +=
7238 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7239 "regular,no_dead_strip\")))= {\n";
7240 for (int i = 0; i < ClsDefCount; i++) {
7241 Result += "\t&OBJC_CLASS_$_";
7242 Result += ClassImplementation[i]->getNameAsString();
7243 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007244 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007245 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007246
7247 if (!DefinedNonLazyClasses.empty()) {
7248 if (LangOpts.MicrosoftExt)
7249 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7250 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7251 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7252 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7253 Result += ",\n";
7254 }
7255 Result += "};\n";
7256 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007257 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007258
7259 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007260 if (LangOpts.MicrosoftExt)
7261 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007262 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7263 Result += llvm::utostr(CatDefCount); Result += "]";
7264 Result +=
7265 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7266 "regular,no_dead_strip\")))= {\n";
7267 for (int i = 0; i < CatDefCount; i++) {
7268 Result += "\t&_OBJC_$_CATEGORY_";
7269 Result +=
7270 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7271 Result += "_$_";
7272 Result += CategoryImplementation[i]->getNameAsString();
7273 Result += ",\n";
7274 }
7275 Result += "};\n";
7276 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007277
7278 if (!DefinedNonLazyCategories.empty()) {
7279 if (LangOpts.MicrosoftExt)
7280 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7281 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7282 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7283 Result += "\t&_OBJC_$_CATEGORY_";
7284 Result +=
7285 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7286 Result += "_$_";
7287 Result += DefinedNonLazyCategories[i]->getNameAsString();
7288 Result += ",\n";
7289 }
7290 Result += "};\n";
7291 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007292}
7293
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007294void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7295 if (LangOpts.MicrosoftExt)
7296 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7297
7298 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7299 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007300 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007301}
7302
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007303/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7304/// implementation.
7305void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7306 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007307 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007308 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7309 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007310 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007311 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7312 CDecl = CDecl->getNextClassCategory())
7313 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7314 break;
7315
7316 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007317 FullCategoryName += "_$_";
7318 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007319
7320 // Build _objc_method_list for class's instance methods if needed
7321 SmallVector<ObjCMethodDecl *, 32>
7322 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7323
7324 // If any of our property implementations have associated getters or
7325 // setters, produce metadata for them as well.
7326 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7327 PropEnd = IDecl->propimpl_end();
7328 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007329 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007330 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007331 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007332 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007333 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007334 if (!PD)
7335 continue;
7336 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7337 InstanceMethods.push_back(Getter);
7338 if (PD->isReadOnly())
7339 continue;
7340 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7341 InstanceMethods.push_back(Setter);
7342 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007343
Fariborz Jahanian61186122012-02-17 18:40:41 +00007344 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7345 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7346 FullCategoryName, true);
7347
7348 SmallVector<ObjCMethodDecl *, 32>
7349 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7350
7351 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7352 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7353 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007354
7355 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007356 // Protocol's super protocol list
7357 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007358 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7359 E = CDecl->protocol_end();
7360
7361 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007362 RefedProtocols.push_back(*I);
7363 // Must write out all protocol definitions in current qualifier list,
7364 // and in their nested qualifiers before writing out current definition.
7365 RewriteObjCProtocolMetaData(*I, Result);
7366 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007367
Fariborz Jahanian61186122012-02-17 18:40:41 +00007368 Write_protocol_list_initializer(Context, Result,
7369 RefedProtocols,
7370 "_OBJC_CATEGORY_PROTOCOLS_$_",
7371 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007372
Fariborz Jahanian61186122012-02-17 18:40:41 +00007373 // Protocol's property metadata.
7374 std::vector<ObjCPropertyDecl *> ClassProperties;
7375 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7376 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007377 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007378
Fariborz Jahanian61186122012-02-17 18:40:41 +00007379 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007380 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007381 "_OBJC_$_PROP_LIST_",
7382 FullCategoryName);
7383
7384 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007385 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007386 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007387 InstanceMethods,
7388 ClassMethods,
7389 RefedProtocols,
7390 ClassProperties);
7391
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007392 // Determine if this category is also "non-lazy".
7393 if (ImplementationIsNonLazy(IDecl))
7394 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007395
7396}
7397
7398void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7399 int CatDefCount = CategoryImplementation.size();
7400 if (!CatDefCount)
7401 return;
7402 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7403 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7404 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7405 for (int i = 0; i < CatDefCount; i++) {
7406 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7407 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7408 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7409 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7410 Result += ClassDecl->getName();
7411 Result += "_$_";
7412 Result += CatDecl->getName();
7413 Result += ",\n";
7414 }
7415 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007416}
7417
7418// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7419/// class methods.
7420template<typename MethodIterator>
7421void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7422 MethodIterator MethodEnd,
7423 bool IsInstanceMethod,
7424 StringRef prefix,
7425 StringRef ClassName,
7426 std::string &Result) {
7427 if (MethodBegin == MethodEnd) return;
7428
7429 if (!objc_impl_method) {
7430 /* struct _objc_method {
7431 SEL _cmd;
7432 char *method_types;
7433 void *_imp;
7434 }
7435 */
7436 Result += "\nstruct _objc_method {\n";
7437 Result += "\tSEL _cmd;\n";
7438 Result += "\tchar *method_types;\n";
7439 Result += "\tvoid *_imp;\n";
7440 Result += "};\n";
7441
7442 objc_impl_method = true;
7443 }
7444
7445 // Build _objc_method_list for class's methods if needed
7446
7447 /* struct {
7448 struct _objc_method_list *next_method;
7449 int method_count;
7450 struct _objc_method method_list[];
7451 }
7452 */
7453 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007454 Result += "\n";
7455 if (LangOpts.MicrosoftExt) {
7456 if (IsInstanceMethod)
7457 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7458 else
7459 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7460 }
7461 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007462 Result += "\tstruct _objc_method_list *next_method;\n";
7463 Result += "\tint method_count;\n";
7464 Result += "\tstruct _objc_method method_list[";
7465 Result += utostr(NumMethods);
7466 Result += "];\n} _OBJC_";
7467 Result += prefix;
7468 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7469 Result += "_METHODS_";
7470 Result += ClassName;
7471 Result += " __attribute__ ((used, section (\"__OBJC, __";
7472 Result += IsInstanceMethod ? "inst" : "cls";
7473 Result += "_meth\")))= ";
7474 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7475
7476 Result += "\t,{{(SEL)\"";
7477 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7478 std::string MethodTypeString;
7479 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7480 Result += "\", \"";
7481 Result += MethodTypeString;
7482 Result += "\", (void *)";
7483 Result += MethodInternalNames[*MethodBegin];
7484 Result += "}\n";
7485 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7486 Result += "\t ,{(SEL)\"";
7487 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7488 std::string MethodTypeString;
7489 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7490 Result += "\", \"";
7491 Result += MethodTypeString;
7492 Result += "\", (void *)";
7493 Result += MethodInternalNames[*MethodBegin];
7494 Result += "}\n";
7495 }
7496 Result += "\t }\n};\n";
7497}
7498
7499Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7500 SourceRange OldRange = IV->getSourceRange();
7501 Expr *BaseExpr = IV->getBase();
7502
7503 // Rewrite the base, but without actually doing replaces.
7504 {
7505 DisableReplaceStmtScope S(*this);
7506 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7507 IV->setBase(BaseExpr);
7508 }
7509
7510 ObjCIvarDecl *D = IV->getDecl();
7511
7512 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007513
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007514 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7515 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007516 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007517 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7518 // lookup which class implements the instance variable.
7519 ObjCInterfaceDecl *clsDeclared = 0;
7520 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7521 clsDeclared);
7522 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7523
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007524 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007525 std::string IvarOffsetName;
7526 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7527
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007528 ReferencedIvars[clsDeclared].insert(D);
7529
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007530 // cast offset to "char *".
7531 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7532 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007533 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007534 BaseExpr);
7535 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7536 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7537 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007538 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7539 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007540 SourceLocation());
7541 BinaryOperator *addExpr =
7542 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7543 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007544 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007545 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007546 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7547 SourceLocation(),
7548 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007549 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007550
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007551 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007552 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007553 RD = RD->getDefinition();
7554 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007555 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007556 ObjCContainerDecl *CDecl =
7557 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7558 // ivar in class extensions requires special treatment.
7559 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7560 CDecl = CatDecl->getClassInterface();
7561 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007562 RecName += "_IMPL";
7563 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7564 SourceLocation(), SourceLocation(),
7565 &Context->Idents.get(RecName.c_str()));
7566 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7567 unsigned UnsignedIntSize =
7568 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7569 Expr *Zero = IntegerLiteral::Create(*Context,
7570 llvm::APInt(UnsignedIntSize, 0),
7571 Context->UnsignedIntTy, SourceLocation());
7572 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7573 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7574 Zero);
7575 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7576 SourceLocation(),
7577 &Context->Idents.get(D->getNameAsString()),
7578 IvarT, 0,
7579 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007580 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007581 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7582 FD->getType(), VK_LValue,
7583 OK_Ordinary);
7584 IvarT = Context->getDecltypeType(ME, ME->getType());
7585 }
7586 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007587 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007588 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007589
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007590 castExpr = NoTypeInfoCStyleCastExpr(Context,
7591 castT,
7592 CK_BitCast,
7593 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007594
7595
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007596 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007597 VK_LValue, OK_Ordinary,
7598 SourceLocation());
7599 PE = new (Context) ParenExpr(OldRange.getBegin(),
7600 OldRange.getEnd(),
7601 Exp);
7602
7603 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007604 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007605
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007606 ReplaceStmtWithRange(IV, Replacement, OldRange);
7607 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007608}