blob: e160f0f434e17e8e336024dfd8ac1574a200efdf [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
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
106
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 Jahanian15f87772012-02-28 22:45:07 +0000113 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
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);
245 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
246 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();
282 void RewriteForwardClassDecl(DeclGroupRef D);
283 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
284 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
285 const std::string &typedefString);
286 void RewriteImplementations();
287 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
288 ObjCImplementationDecl *IMD,
289 ObjCCategoryImplDecl *CID);
290 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
291 void RewriteImplementationDecl(Decl *Dcl);
292 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
293 ObjCMethodDecl *MDecl, std::string &ResultStr);
294 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
295 const FunctionType *&FPRetType);
296 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
297 ValueDecl *VD, bool def=false);
298 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
299 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
300 void RewriteForwardProtocolDecl(DeclGroupRef D);
301 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
302 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
303 void RewriteProperty(ObjCPropertyDecl *prop);
304 void RewriteFunctionDecl(FunctionDecl *FD);
305 void RewriteBlockPointerType(std::string& Str, QualType Type);
306 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
307 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
308 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
309 void RewriteTypeOfDecl(VarDecl *VD);
310 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
311
312 // Expression Rewriting.
313 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
314 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
315 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
317 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
318 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
319 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000320 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +0000321 Stmt *RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000322 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000323 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000324 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
325 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
326 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
327 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
328 SourceLocation OrigEnd);
329 Stmt *RewriteBreakStmt(BreakStmt *S);
330 Stmt *RewriteContinueStmt(ContinueStmt *S);
331 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000332 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000333
334 // Block rewriting.
335 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
336
337 // Block specific rewrite rules.
338 void RewriteBlockPointerDecl(NamedDecl *VD);
339 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000340 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000341 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
342 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
343
344 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
345 std::string &Result);
346
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000347 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
348
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000349 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
350
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000351 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
352 std::string &Result);
353
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000354 virtual void Initialize(ASTContext &context);
355
356 // Misc. AST transformation routines. Somtimes they end up calling
357 // rewriting routines on the new ASTs.
358 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
359 Expr **args, unsigned nargs,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
364 SourceLocation StartLoc=SourceLocation(),
365 SourceLocation EndLoc=SourceLocation());
366
367 void SynthCountByEnumWithState(std::string &buf);
368 void SynthMsgSendFunctionDecl();
369 void SynthMsgSendSuperFunctionDecl();
370 void SynthMsgSendStretFunctionDecl();
371 void SynthMsgSendFpretFunctionDecl();
372 void SynthMsgSendSuperStretFunctionDecl();
373 void SynthGetClassFunctionDecl();
374 void SynthGetMetaClassFunctionDecl();
375 void SynthGetSuperClassFunctionDecl();
376 void SynthSelGetUidFunctionDecl();
377 void SynthSuperContructorFunctionDecl();
378
379 // Rewriting metadata
380 template<typename MethodIterator>
381 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
382 MethodIterator MethodEnd,
383 bool IsInstanceMethod,
384 StringRef prefix,
385 StringRef ClassName,
386 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000387 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
388 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000389 virtual void RewriteObjCProtocolListMetaData(
390 const ObjCList<ObjCProtocolDecl> &Prots,
391 StringRef prefix, StringRef ClassName, std::string &Result);
392 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
393 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000394 virtual void RewriteClassSetupInitHook(std::string &Result);
395
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000396 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000397 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000398 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
399 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000400 virtual void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000401
402 // Rewriting ivar
403 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
404 std::string &Result);
405 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
406
407
408 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
409 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
410 StringRef funcName, std::string Tag);
411 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
412 StringRef funcName, std::string Tag);
413 std::string SynthesizeBlockImpl(BlockExpr *CE,
414 std::string Tag, std::string Desc);
415 std::string SynthesizeBlockDescriptor(std::string DescTag,
416 std::string ImplTag,
417 int i, StringRef funcName,
418 unsigned hasCopy);
419 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
420 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
421 StringRef FunName);
422 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
423 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000424 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000425
426 // Misc. helper routines.
427 QualType getProtocolType();
428 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000429 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
430 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
431 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
432
433 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
434 void CollectBlockDeclRefInfo(BlockExpr *Exp);
435 void GetBlockDeclRefExprs(Stmt *S);
436 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000437 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000438 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
439
440 // We avoid calling Type::isBlockPointerType(), since it operates on the
441 // canonical type. We only care if the top-level type is a closure pointer.
442 bool isTopLevelBlockPointerType(QualType T) {
443 return isa<BlockPointerType>(T);
444 }
445
446 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
447 /// to a function pointer type and upon success, returns true; false
448 /// otherwise.
449 bool convertBlockPointerToFunctionPointer(QualType &T) {
450 if (isTopLevelBlockPointerType(T)) {
451 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
452 T = Context->getPointerType(BPT->getPointeeType());
453 return true;
454 }
455 return false;
456 }
457
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000458 bool convertObjCTypeToCStyleType(QualType &T);
459
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000460 bool needToScanForQualifiers(QualType T);
461 QualType getSuperStructType();
462 QualType getConstantStringStructType();
463 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
464 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
465
466 void convertToUnqualifiedObjCType(QualType &T) {
467 if (T->isObjCQualifiedIdType())
468 T = Context->getObjCIdType();
469 else if (T->isObjCQualifiedClassType())
470 T = Context->getObjCClassType();
471 else if (T->isObjCObjectPointerType() &&
472 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
473 if (const ObjCObjectPointerType * OBJPT =
474 T->getAsObjCInterfacePointerType()) {
475 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
476 T = QualType(IFaceT, 0);
477 T = Context->getPointerType(T);
478 }
479 }
480 }
481
482 // FIXME: This predicate seems like it would be useful to add to ASTContext.
483 bool isObjCType(QualType T) {
484 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
485 return false;
486
487 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
488
489 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
490 OCT == Context->getCanonicalType(Context->getObjCClassType()))
491 return true;
492
493 if (const PointerType *PT = OCT->getAs<PointerType>()) {
494 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
495 PT->getPointeeType()->isObjCQualifiedIdType())
496 return true;
497 }
498 return false;
499 }
500 bool PointerTypeTakesAnyBlockArguments(QualType QT);
501 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
502 void GetExtentOfArgList(const char *Name, const char *&LParen,
503 const char *&RParen);
504
505 void QuoteDoublequotes(std::string &From, std::string &To) {
506 for (unsigned i = 0; i < From.length(); i++) {
507 if (From[i] == '"')
508 To += "\\\"";
509 else
510 To += From[i];
511 }
512 }
513
514 QualType getSimpleFunctionType(QualType result,
515 const QualType *args,
516 unsigned numArgs,
517 bool variadic = false) {
518 if (result == Context->getObjCInstanceType())
519 result = Context->getObjCIdType();
520 FunctionProtoType::ExtProtoInfo fpi;
521 fpi.Variadic = variadic;
522 return Context->getFunctionType(result, args, numArgs, fpi);
523 }
524
525 // Helper function: create a CStyleCastExpr with trivial type source info.
526 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
527 CastKind Kind, Expr *E) {
528 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
529 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
530 SourceLocation(), SourceLocation());
531 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000532
533 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
534 IdentifierInfo* II = &Context->Idents.get("load");
535 Selector LoadSel = Context->Selectors.getSelector(0, &II);
536 return OD->getClassMethod(LoadSel) != 0;
537 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000538 };
539
540}
541
542void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
543 NamedDecl *D) {
544 if (const FunctionProtoType *fproto
545 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
546 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
547 E = fproto->arg_type_end(); I && (I != E); ++I)
548 if (isTopLevelBlockPointerType(*I)) {
549 // All the args are checked/rewritten. Don't call twice!
550 RewriteBlockPointerDecl(D);
551 break;
552 }
553 }
554}
555
556void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
557 const PointerType *PT = funcType->getAs<PointerType>();
558 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
559 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
560}
561
562static bool IsHeaderFile(const std::string &Filename) {
563 std::string::size_type DotPos = Filename.rfind('.');
564
565 if (DotPos == std::string::npos) {
566 // no file extension
567 return false;
568 }
569
570 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
571 // C header: .h
572 // C++ header: .hh or .H;
573 return Ext == "h" || Ext == "hh" || Ext == "H";
574}
575
576RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
577 DiagnosticsEngine &D, const LangOptions &LOpts,
578 bool silenceMacroWarn)
579 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
580 SilenceRewriteMacroWarning(silenceMacroWarn) {
581 IsHeader = IsHeaderFile(inFile);
582 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
583 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000584 // FIXME. This should be an error. But if block is not called, it is OK. And it
585 // may break including some headers.
586 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
587 "rewriting block literal declared in global scope is not implemented");
588
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000589 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
590 DiagnosticsEngine::Warning,
591 "rewriter doesn't support user-specified control flow semantics "
592 "for @try/@finally (code may not execute properly)");
593}
594
595ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
596 raw_ostream* OS,
597 DiagnosticsEngine &Diags,
598 const LangOptions &LOpts,
599 bool SilenceRewriteMacroWarning) {
600 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
601}
602
603void RewriteModernObjC::InitializeCommon(ASTContext &context) {
604 Context = &context;
605 SM = &Context->getSourceManager();
606 TUDecl = Context->getTranslationUnitDecl();
607 MsgSendFunctionDecl = 0;
608 MsgSendSuperFunctionDecl = 0;
609 MsgSendStretFunctionDecl = 0;
610 MsgSendSuperStretFunctionDecl = 0;
611 MsgSendFpretFunctionDecl = 0;
612 GetClassFunctionDecl = 0;
613 GetMetaClassFunctionDecl = 0;
614 GetSuperClassFunctionDecl = 0;
615 SelGetUidFunctionDecl = 0;
616 CFStringFunctionDecl = 0;
617 ConstantStringClassReference = 0;
618 NSStringRecord = 0;
619 CurMethodDef = 0;
620 CurFunctionDef = 0;
621 CurFunctionDeclToDeclareForBlock = 0;
622 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000623 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000624 SuperStructDecl = 0;
625 ProtocolTypeDecl = 0;
626 ConstantStringDecl = 0;
627 BcLabelCount = 0;
628 SuperContructorFunctionDecl = 0;
629 NumObjCStringLiterals = 0;
630 PropParentMap = 0;
631 CurrentBody = 0;
632 DisableReplaceStmt = false;
633 objc_impl_method = false;
634
635 // Get the ID and start/end of the main file.
636 MainFileID = SM->getMainFileID();
637 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
638 MainFileStart = MainBuf->getBufferStart();
639 MainFileEnd = MainBuf->getBufferEnd();
640
David Blaikie4e4d0842012-03-11 07:00:24 +0000641 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000642}
643
644//===----------------------------------------------------------------------===//
645// Top Level Driver Code
646//===----------------------------------------------------------------------===//
647
648void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
649 if (Diags.hasErrorOccurred())
650 return;
651
652 // Two cases: either the decl could be in the main file, or it could be in a
653 // #included file. If the former, rewrite it now. If the later, check to see
654 // if we rewrote the #include/#import.
655 SourceLocation Loc = D->getLocation();
656 Loc = SM->getExpansionLoc(Loc);
657
658 // If this is for a builtin, ignore it.
659 if (Loc.isInvalid()) return;
660
661 // Look for built-in declarations that we need to refer during the rewrite.
662 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
663 RewriteFunctionDecl(FD);
664 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
665 // declared in <Foundation/NSString.h>
666 if (FVD->getName() == "_NSConstantStringClassReference") {
667 ConstantStringClassReference = FVD;
668 return;
669 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000670 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
671 RewriteCategoryDecl(CD);
672 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
673 if (PD->isThisDeclarationADefinition())
674 RewriteProtocolDecl(PD);
675 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000676 // FIXME. This will not work in all situations and leaving it out
677 // is harmless.
678 // RewriteLinkageSpec(LSD);
679
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000680 // Recurse into linkage specifications
681 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
682 DIEnd = LSD->decls_end();
683 DI != DIEnd; ) {
684 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
685 if (!IFace->isThisDeclarationADefinition()) {
686 SmallVector<Decl *, 8> DG;
687 SourceLocation StartLoc = IFace->getLocStart();
688 do {
689 if (isa<ObjCInterfaceDecl>(*DI) &&
690 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
691 StartLoc == (*DI)->getLocStart())
692 DG.push_back(*DI);
693 else
694 break;
695
696 ++DI;
697 } while (DI != DIEnd);
698 RewriteForwardClassDecl(DG);
699 continue;
700 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000701 else {
702 // Keep track of all interface declarations seen.
703 ObjCInterfacesSeen.push_back(IFace);
704 ++DI;
705 continue;
706 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000707 }
708
709 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
710 if (!Proto->isThisDeclarationADefinition()) {
711 SmallVector<Decl *, 8> DG;
712 SourceLocation StartLoc = Proto->getLocStart();
713 do {
714 if (isa<ObjCProtocolDecl>(*DI) &&
715 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
716 StartLoc == (*DI)->getLocStart())
717 DG.push_back(*DI);
718 else
719 break;
720
721 ++DI;
722 } while (DI != DIEnd);
723 RewriteForwardProtocolDecl(DG);
724 continue;
725 }
726 }
727
728 HandleTopLevelSingleDecl(*DI);
729 ++DI;
730 }
731 }
732 // If we have a decl in the main file, see if we should rewrite it.
733 if (SM->isFromMainFile(Loc))
734 return HandleDeclInMainFile(D);
735}
736
737//===----------------------------------------------------------------------===//
738// Syntactic (non-AST) Rewriting Code
739//===----------------------------------------------------------------------===//
740
741void RewriteModernObjC::RewriteInclude() {
742 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
743 StringRef MainBuf = SM->getBufferData(MainFileID);
744 const char *MainBufStart = MainBuf.begin();
745 const char *MainBufEnd = MainBuf.end();
746 size_t ImportLen = strlen("import");
747
748 // Loop over the whole file, looking for includes.
749 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
750 if (*BufPtr == '#') {
751 if (++BufPtr == MainBufEnd)
752 return;
753 while (*BufPtr == ' ' || *BufPtr == '\t')
754 if (++BufPtr == MainBufEnd)
755 return;
756 if (!strncmp(BufPtr, "import", ImportLen)) {
757 // replace import with include
758 SourceLocation ImportLoc =
759 LocStart.getLocWithOffset(BufPtr-MainBufStart);
760 ReplaceText(ImportLoc, ImportLen, "include");
761 BufPtr += ImportLen;
762 }
763 }
764 }
765}
766
767static std::string getIvarAccessString(ObjCIvarDecl *OID) {
768 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
769 std::string S;
770 S = "((struct ";
771 S += ClassDecl->getIdentifier()->getName();
772 S += "_IMPL *)self)->";
773 S += OID->getName();
774 return S;
775}
776
777void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
778 ObjCImplementationDecl *IMD,
779 ObjCCategoryImplDecl *CID) {
780 static bool objcGetPropertyDefined = false;
781 static bool objcSetPropertyDefined = false;
782 SourceLocation startLoc = PID->getLocStart();
783 InsertText(startLoc, "// ");
784 const char *startBuf = SM->getCharacterData(startLoc);
785 assert((*startBuf == '@') && "bogus @synthesize location");
786 const char *semiBuf = strchr(startBuf, ';');
787 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
788 SourceLocation onePastSemiLoc =
789 startLoc.getLocWithOffset(semiBuf-startBuf+1);
790
791 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
792 return; // FIXME: is this correct?
793
794 // Generate the 'getter' function.
795 ObjCPropertyDecl *PD = PID->getPropertyDecl();
796 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
797
798 if (!OID)
799 return;
800 unsigned Attributes = PD->getPropertyAttributes();
801 if (!PD->getGetterMethodDecl()->isDefined()) {
802 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
803 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
804 ObjCPropertyDecl::OBJC_PR_copy));
805 std::string Getr;
806 if (GenGetProperty && !objcGetPropertyDefined) {
807 objcGetPropertyDefined = true;
808 // FIXME. Is this attribute correct in all cases?
809 Getr = "\nextern \"C\" __declspec(dllimport) "
810 "id objc_getProperty(id, SEL, long, bool);\n";
811 }
812 RewriteObjCMethodDecl(OID->getContainingInterface(),
813 PD->getGetterMethodDecl(), Getr);
814 Getr += "{ ";
815 // Synthesize an explicit cast to gain access to the ivar.
816 // See objc-act.c:objc_synthesize_new_getter() for details.
817 if (GenGetProperty) {
818 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
819 Getr += "typedef ";
820 const FunctionType *FPRetType = 0;
821 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
822 FPRetType);
823 Getr += " _TYPE";
824 if (FPRetType) {
825 Getr += ")"; // close the precedence "scope" for "*".
826
827 // Now, emit the argument types (if any).
828 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
829 Getr += "(";
830 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
831 if (i) Getr += ", ";
832 std::string ParamStr = FT->getArgType(i).getAsString(
833 Context->getPrintingPolicy());
834 Getr += ParamStr;
835 }
836 if (FT->isVariadic()) {
837 if (FT->getNumArgs()) Getr += ", ";
838 Getr += "...";
839 }
840 Getr += ")";
841 } else
842 Getr += "()";
843 }
844 Getr += ";\n";
845 Getr += "return (_TYPE)";
846 Getr += "objc_getProperty(self, _cmd, ";
847 RewriteIvarOffsetComputation(OID, Getr);
848 Getr += ", 1)";
849 }
850 else
851 Getr += "return " + getIvarAccessString(OID);
852 Getr += "; }";
853 InsertText(onePastSemiLoc, Getr);
854 }
855
856 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
857 return;
858
859 // Generate the 'setter' function.
860 std::string Setr;
861 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
862 ObjCPropertyDecl::OBJC_PR_copy);
863 if (GenSetProperty && !objcSetPropertyDefined) {
864 objcSetPropertyDefined = true;
865 // FIXME. Is this attribute correct in all cases?
866 Setr = "\nextern \"C\" __declspec(dllimport) "
867 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
868 }
869
870 RewriteObjCMethodDecl(OID->getContainingInterface(),
871 PD->getSetterMethodDecl(), Setr);
872 Setr += "{ ";
873 // Synthesize an explicit cast to initialize the ivar.
874 // See objc-act.c:objc_synthesize_new_setter() for details.
875 if (GenSetProperty) {
876 Setr += "objc_setProperty (self, _cmd, ";
877 RewriteIvarOffsetComputation(OID, Setr);
878 Setr += ", (id)";
879 Setr += PD->getName();
880 Setr += ", ";
881 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
882 Setr += "0, ";
883 else
884 Setr += "1, ";
885 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
886 Setr += "1)";
887 else
888 Setr += "0)";
889 }
890 else {
891 Setr += getIvarAccessString(OID) + " = ";
892 Setr += PD->getName();
893 }
894 Setr += "; }";
895 InsertText(onePastSemiLoc, Setr);
896}
897
898static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
899 std::string &typedefString) {
900 typedefString += "#ifndef _REWRITER_typedef_";
901 typedefString += ForwardDecl->getNameAsString();
902 typedefString += "\n";
903 typedefString += "#define _REWRITER_typedef_";
904 typedefString += ForwardDecl->getNameAsString();
905 typedefString += "\n";
906 typedefString += "typedef struct objc_object ";
907 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000908 // typedef struct { } _objc_exc_Classname;
909 typedefString += ";\ntypedef struct {} _objc_exc_";
910 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000911 typedefString += ";\n#endif\n";
912}
913
914void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
915 const std::string &typedefString) {
916 SourceLocation startLoc = ClassDecl->getLocStart();
917 const char *startBuf = SM->getCharacterData(startLoc);
918 const char *semiPtr = strchr(startBuf, ';');
919 // Replace the @class with typedefs corresponding to the classes.
920 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
921}
922
923void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
924 std::string typedefString;
925 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
926 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
927 if (I == D.begin()) {
928 // Translate to typedef's that forward reference structs with the same name
929 // as the class. As a convenience, we include the original declaration
930 // as a comment.
931 typedefString += "// @class ";
932 typedefString += ForwardDecl->getNameAsString();
933 typedefString += ";\n";
934 }
935 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
936 }
937 DeclGroupRef::iterator I = D.begin();
938 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
939}
940
941void RewriteModernObjC::RewriteForwardClassDecl(
942 const llvm::SmallVector<Decl*, 8> &D) {
943 std::string typedefString;
944 for (unsigned i = 0; i < D.size(); i++) {
945 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
946 if (i == 0) {
947 typedefString += "// @class ";
948 typedefString += ForwardDecl->getNameAsString();
949 typedefString += ";\n";
950 }
951 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
952 }
953 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
954}
955
956void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
957 // When method is a synthesized one, such as a getter/setter there is
958 // nothing to rewrite.
959 if (Method->isImplicit())
960 return;
961 SourceLocation LocStart = Method->getLocStart();
962 SourceLocation LocEnd = Method->getLocEnd();
963
964 if (SM->getExpansionLineNumber(LocEnd) >
965 SM->getExpansionLineNumber(LocStart)) {
966 InsertText(LocStart, "#if 0\n");
967 ReplaceText(LocEnd, 1, ";\n#endif\n");
968 } else {
969 InsertText(LocStart, "// ");
970 }
971}
972
973void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
974 SourceLocation Loc = prop->getAtLoc();
975
976 ReplaceText(Loc, 0, "// ");
977 // FIXME: handle properties that are declared across multiple lines.
978}
979
980void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
981 SourceLocation LocStart = CatDecl->getLocStart();
982
983 // FIXME: handle category headers that are declared across multiple lines.
984 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000985 if (CatDecl->getIvarLBraceLoc().isValid())
986 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000987 for (ObjCCategoryDecl::ivar_iterator
988 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
989 ObjCIvarDecl *Ivar = (*I);
990 SourceLocation LocStart = Ivar->getLocStart();
991 ReplaceText(LocStart, 0, "// ");
992 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000993 if (CatDecl->getIvarRBraceLoc().isValid())
994 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
995
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000996 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
997 E = CatDecl->prop_end(); I != E; ++I)
998 RewriteProperty(*I);
999
1000 for (ObjCCategoryDecl::instmeth_iterator
1001 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1002 I != E; ++I)
1003 RewriteMethodDeclaration(*I);
1004 for (ObjCCategoryDecl::classmeth_iterator
1005 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1006 I != E; ++I)
1007 RewriteMethodDeclaration(*I);
1008
1009 // Lastly, comment out the @end.
1010 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1011 strlen("@end"), "/* @end */");
1012}
1013
1014void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1015 SourceLocation LocStart = PDecl->getLocStart();
1016 assert(PDecl->isThisDeclarationADefinition());
1017
1018 // FIXME: handle protocol headers that are declared across multiple lines.
1019 ReplaceText(LocStart, 0, "// ");
1020
1021 for (ObjCProtocolDecl::instmeth_iterator
1022 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1023 I != E; ++I)
1024 RewriteMethodDeclaration(*I);
1025 for (ObjCProtocolDecl::classmeth_iterator
1026 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1027 I != E; ++I)
1028 RewriteMethodDeclaration(*I);
1029
1030 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1031 E = PDecl->prop_end(); I != E; ++I)
1032 RewriteProperty(*I);
1033
1034 // Lastly, comment out the @end.
1035 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1036 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1037
1038 // Must comment out @optional/@required
1039 const char *startBuf = SM->getCharacterData(LocStart);
1040 const char *endBuf = SM->getCharacterData(LocEnd);
1041 for (const char *p = startBuf; p < endBuf; p++) {
1042 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1043 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1044 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1045
1046 }
1047 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1048 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1049 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1050
1051 }
1052 }
1053}
1054
1055void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1056 SourceLocation LocStart = (*D.begin())->getLocStart();
1057 if (LocStart.isInvalid())
1058 llvm_unreachable("Invalid SourceLocation");
1059 // FIXME: handle forward protocol that are declared across multiple lines.
1060 ReplaceText(LocStart, 0, "// ");
1061}
1062
1063void
1064RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1065 SourceLocation LocStart = DG[0]->getLocStart();
1066 if (LocStart.isInvalid())
1067 llvm_unreachable("Invalid SourceLocation");
1068 // FIXME: handle forward protocol that are declared across multiple lines.
1069 ReplaceText(LocStart, 0, "// ");
1070}
1071
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001072void
1073RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1074 SourceLocation LocStart = LSD->getExternLoc();
1075 if (LocStart.isInvalid())
1076 llvm_unreachable("Invalid extern SourceLocation");
1077
1078 ReplaceText(LocStart, 0, "// ");
1079 if (!LSD->hasBraces())
1080 return;
1081 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1082 SourceLocation LocRBrace = LSD->getRBraceLoc();
1083 if (LocRBrace.isInvalid())
1084 llvm_unreachable("Invalid rbrace SourceLocation");
1085 ReplaceText(LocRBrace, 0, "// ");
1086}
1087
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001088void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1089 const FunctionType *&FPRetType) {
1090 if (T->isObjCQualifiedIdType())
1091 ResultStr += "id";
1092 else if (T->isFunctionPointerType() ||
1093 T->isBlockPointerType()) {
1094 // needs special handling, since pointer-to-functions have special
1095 // syntax (where a decaration models use).
1096 QualType retType = T;
1097 QualType PointeeTy;
1098 if (const PointerType* PT = retType->getAs<PointerType>())
1099 PointeeTy = PT->getPointeeType();
1100 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1101 PointeeTy = BPT->getPointeeType();
1102 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1103 ResultStr += FPRetType->getResultType().getAsString(
1104 Context->getPrintingPolicy());
1105 ResultStr += "(*";
1106 }
1107 } else
1108 ResultStr += T.getAsString(Context->getPrintingPolicy());
1109}
1110
1111void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1112 ObjCMethodDecl *OMD,
1113 std::string &ResultStr) {
1114 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1115 const FunctionType *FPRetType = 0;
1116 ResultStr += "\nstatic ";
1117 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1118 ResultStr += " ";
1119
1120 // Unique method name
1121 std::string NameStr;
1122
1123 if (OMD->isInstanceMethod())
1124 NameStr += "_I_";
1125 else
1126 NameStr += "_C_";
1127
1128 NameStr += IDecl->getNameAsString();
1129 NameStr += "_";
1130
1131 if (ObjCCategoryImplDecl *CID =
1132 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1133 NameStr += CID->getNameAsString();
1134 NameStr += "_";
1135 }
1136 // Append selector names, replacing ':' with '_'
1137 {
1138 std::string selString = OMD->getSelector().getAsString();
1139 int len = selString.size();
1140 for (int i = 0; i < len; i++)
1141 if (selString[i] == ':')
1142 selString[i] = '_';
1143 NameStr += selString;
1144 }
1145 // Remember this name for metadata emission
1146 MethodInternalNames[OMD] = NameStr;
1147 ResultStr += NameStr;
1148
1149 // Rewrite arguments
1150 ResultStr += "(";
1151
1152 // invisible arguments
1153 if (OMD->isInstanceMethod()) {
1154 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1155 selfTy = Context->getPointerType(selfTy);
1156 if (!LangOpts.MicrosoftExt) {
1157 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1158 ResultStr += "struct ";
1159 }
1160 // When rewriting for Microsoft, explicitly omit the structure name.
1161 ResultStr += IDecl->getNameAsString();
1162 ResultStr += " *";
1163 }
1164 else
1165 ResultStr += Context->getObjCClassType().getAsString(
1166 Context->getPrintingPolicy());
1167
1168 ResultStr += " self, ";
1169 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1170 ResultStr += " _cmd";
1171
1172 // Method arguments.
1173 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1174 E = OMD->param_end(); PI != E; ++PI) {
1175 ParmVarDecl *PDecl = *PI;
1176 ResultStr += ", ";
1177 if (PDecl->getType()->isObjCQualifiedIdType()) {
1178 ResultStr += "id ";
1179 ResultStr += PDecl->getNameAsString();
1180 } else {
1181 std::string Name = PDecl->getNameAsString();
1182 QualType QT = PDecl->getType();
1183 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001184 (void)convertBlockPointerToFunctionPointer(QT);
1185 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001186 ResultStr += Name;
1187 }
1188 }
1189 if (OMD->isVariadic())
1190 ResultStr += ", ...";
1191 ResultStr += ") ";
1192
1193 if (FPRetType) {
1194 ResultStr += ")"; // close the precedence "scope" for "*".
1195
1196 // Now, emit the argument types (if any).
1197 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1198 ResultStr += "(";
1199 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1200 if (i) ResultStr += ", ";
1201 std::string ParamStr = FT->getArgType(i).getAsString(
1202 Context->getPrintingPolicy());
1203 ResultStr += ParamStr;
1204 }
1205 if (FT->isVariadic()) {
1206 if (FT->getNumArgs()) ResultStr += ", ";
1207 ResultStr += "...";
1208 }
1209 ResultStr += ")";
1210 } else {
1211 ResultStr += "()";
1212 }
1213 }
1214}
1215void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1216 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1217 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1218
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001219 if (IMD) {
1220 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001221 if (IMD->getIvarLBraceLoc().isValid())
1222 InsertText(IMD->getIvarLBraceLoc(), "// ");
1223 for (ObjCImplementationDecl::ivar_iterator
1224 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1225 ObjCIvarDecl *Ivar = (*I);
1226 SourceLocation LocStart = Ivar->getLocStart();
1227 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001228 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001229 if (IMD->getIvarRBraceLoc().isValid())
1230 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001231 }
1232 else
1233 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001234
1235 for (ObjCCategoryImplDecl::instmeth_iterator
1236 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1237 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1238 I != E; ++I) {
1239 std::string ResultStr;
1240 ObjCMethodDecl *OMD = *I;
1241 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1242 SourceLocation LocStart = OMD->getLocStart();
1243 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1244
1245 const char *startBuf = SM->getCharacterData(LocStart);
1246 const char *endBuf = SM->getCharacterData(LocEnd);
1247 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1248 }
1249
1250 for (ObjCCategoryImplDecl::classmeth_iterator
1251 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1252 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1253 I != E; ++I) {
1254 std::string ResultStr;
1255 ObjCMethodDecl *OMD = *I;
1256 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1257 SourceLocation LocStart = OMD->getLocStart();
1258 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1259
1260 const char *startBuf = SM->getCharacterData(LocStart);
1261 const char *endBuf = SM->getCharacterData(LocEnd);
1262 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1263 }
1264 for (ObjCCategoryImplDecl::propimpl_iterator
1265 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1266 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1267 I != E; ++I) {
1268 RewritePropertyImplDecl(*I, IMD, CID);
1269 }
1270
1271 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1272}
1273
1274void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001275 // Do not synthesize more than once.
1276 if (ObjCSynthesizedStructs.count(ClassDecl))
1277 return;
1278 // Make sure super class's are written before current class is written.
1279 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1280 while (SuperClass) {
1281 RewriteInterfaceDecl(SuperClass);
1282 SuperClass = SuperClass->getSuperClass();
1283 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001284 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001285 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001286 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001287 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001288 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1289
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001290 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001291 // Mark this typedef as having been written into its c++ equivalent.
1292 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001293
1294 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001295 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001296 RewriteProperty(*I);
1297 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001298 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001299 I != E; ++I)
1300 RewriteMethodDeclaration(*I);
1301 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001302 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001303 I != E; ++I)
1304 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001305
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001306 // Lastly, comment out the @end.
1307 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1308 "/* @end */");
1309 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001310}
1311
1312Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1313 SourceRange OldRange = PseudoOp->getSourceRange();
1314
1315 // We just magically know some things about the structure of this
1316 // expression.
1317 ObjCMessageExpr *OldMsg =
1318 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1319 PseudoOp->getNumSemanticExprs() - 1));
1320
1321 // Because the rewriter doesn't allow us to rewrite rewritten code,
1322 // we need to suppress rewriting the sub-statements.
1323 Expr *Base, *RHS;
1324 {
1325 DisableReplaceStmtScope S(*this);
1326
1327 // Rebuild the base expression if we have one.
1328 Base = 0;
1329 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1330 Base = OldMsg->getInstanceReceiver();
1331 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1332 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1333 }
1334
1335 // Rebuild the RHS.
1336 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1337 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1338 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1339 }
1340
1341 // TODO: avoid this copy.
1342 SmallVector<SourceLocation, 1> SelLocs;
1343 OldMsg->getSelectorLocs(SelLocs);
1344
1345 ObjCMessageExpr *NewMsg = 0;
1346 switch (OldMsg->getReceiverKind()) {
1347 case ObjCMessageExpr::Class:
1348 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1349 OldMsg->getValueKind(),
1350 OldMsg->getLeftLoc(),
1351 OldMsg->getClassReceiverTypeInfo(),
1352 OldMsg->getSelector(),
1353 SelLocs,
1354 OldMsg->getMethodDecl(),
1355 RHS,
1356 OldMsg->getRightLoc(),
1357 OldMsg->isImplicit());
1358 break;
1359
1360 case ObjCMessageExpr::Instance:
1361 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1362 OldMsg->getValueKind(),
1363 OldMsg->getLeftLoc(),
1364 Base,
1365 OldMsg->getSelector(),
1366 SelLocs,
1367 OldMsg->getMethodDecl(),
1368 RHS,
1369 OldMsg->getRightLoc(),
1370 OldMsg->isImplicit());
1371 break;
1372
1373 case ObjCMessageExpr::SuperClass:
1374 case ObjCMessageExpr::SuperInstance:
1375 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1376 OldMsg->getValueKind(),
1377 OldMsg->getLeftLoc(),
1378 OldMsg->getSuperLoc(),
1379 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1380 OldMsg->getSuperType(),
1381 OldMsg->getSelector(),
1382 SelLocs,
1383 OldMsg->getMethodDecl(),
1384 RHS,
1385 OldMsg->getRightLoc(),
1386 OldMsg->isImplicit());
1387 break;
1388 }
1389
1390 Stmt *Replacement = SynthMessageExpr(NewMsg);
1391 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1392 return Replacement;
1393}
1394
1395Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1396 SourceRange OldRange = PseudoOp->getSourceRange();
1397
1398 // We just magically know some things about the structure of this
1399 // expression.
1400 ObjCMessageExpr *OldMsg =
1401 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1402
1403 // Because the rewriter doesn't allow us to rewrite rewritten code,
1404 // we need to suppress rewriting the sub-statements.
1405 Expr *Base = 0;
1406 {
1407 DisableReplaceStmtScope S(*this);
1408
1409 // Rebuild the base expression if we have one.
1410 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1411 Base = OldMsg->getInstanceReceiver();
1412 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1413 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1414 }
1415 }
1416
1417 // Intentionally empty.
1418 SmallVector<SourceLocation, 1> SelLocs;
1419 SmallVector<Expr*, 1> Args;
1420
1421 ObjCMessageExpr *NewMsg = 0;
1422 switch (OldMsg->getReceiverKind()) {
1423 case ObjCMessageExpr::Class:
1424 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1425 OldMsg->getValueKind(),
1426 OldMsg->getLeftLoc(),
1427 OldMsg->getClassReceiverTypeInfo(),
1428 OldMsg->getSelector(),
1429 SelLocs,
1430 OldMsg->getMethodDecl(),
1431 Args,
1432 OldMsg->getRightLoc(),
1433 OldMsg->isImplicit());
1434 break;
1435
1436 case ObjCMessageExpr::Instance:
1437 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1438 OldMsg->getValueKind(),
1439 OldMsg->getLeftLoc(),
1440 Base,
1441 OldMsg->getSelector(),
1442 SelLocs,
1443 OldMsg->getMethodDecl(),
1444 Args,
1445 OldMsg->getRightLoc(),
1446 OldMsg->isImplicit());
1447 break;
1448
1449 case ObjCMessageExpr::SuperClass:
1450 case ObjCMessageExpr::SuperInstance:
1451 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1452 OldMsg->getValueKind(),
1453 OldMsg->getLeftLoc(),
1454 OldMsg->getSuperLoc(),
1455 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1456 OldMsg->getSuperType(),
1457 OldMsg->getSelector(),
1458 SelLocs,
1459 OldMsg->getMethodDecl(),
1460 Args,
1461 OldMsg->getRightLoc(),
1462 OldMsg->isImplicit());
1463 break;
1464 }
1465
1466 Stmt *Replacement = SynthMessageExpr(NewMsg);
1467 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1468 return Replacement;
1469}
1470
1471/// SynthCountByEnumWithState - To print:
1472/// ((unsigned int (*)
1473/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1474/// (void *)objc_msgSend)((id)l_collection,
1475/// sel_registerName(
1476/// "countByEnumeratingWithState:objects:count:"),
1477/// &enumState,
1478/// (id *)__rw_items, (unsigned int)16)
1479///
1480void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1481 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1482 "id *, unsigned int))(void *)objc_msgSend)";
1483 buf += "\n\t\t";
1484 buf += "((id)l_collection,\n\t\t";
1485 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1486 buf += "\n\t\t";
1487 buf += "&enumState, "
1488 "(id *)__rw_items, (unsigned int)16)";
1489}
1490
1491/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1492/// statement to exit to its outer synthesized loop.
1493///
1494Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1495 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1496 return S;
1497 // replace break with goto __break_label
1498 std::string buf;
1499
1500 SourceLocation startLoc = S->getLocStart();
1501 buf = "goto __break_label_";
1502 buf += utostr(ObjCBcLabelNo.back());
1503 ReplaceText(startLoc, strlen("break"), buf);
1504
1505 return 0;
1506}
1507
1508/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1509/// statement to continue with its inner synthesized loop.
1510///
1511Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1512 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1513 return S;
1514 // replace continue with goto __continue_label
1515 std::string buf;
1516
1517 SourceLocation startLoc = S->getLocStart();
1518 buf = "goto __continue_label_";
1519 buf += utostr(ObjCBcLabelNo.back());
1520 ReplaceText(startLoc, strlen("continue"), buf);
1521
1522 return 0;
1523}
1524
1525/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1526/// It rewrites:
1527/// for ( type elem in collection) { stmts; }
1528
1529/// Into:
1530/// {
1531/// type elem;
1532/// struct __objcFastEnumerationState enumState = { 0 };
1533/// id __rw_items[16];
1534/// id l_collection = (id)collection;
1535/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1536/// objects:__rw_items count:16];
1537/// if (limit) {
1538/// unsigned long startMutations = *enumState.mutationsPtr;
1539/// do {
1540/// unsigned long counter = 0;
1541/// do {
1542/// if (startMutations != *enumState.mutationsPtr)
1543/// objc_enumerationMutation(l_collection);
1544/// elem = (type)enumState.itemsPtr[counter++];
1545/// stmts;
1546/// __continue_label: ;
1547/// } while (counter < limit);
1548/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1549/// objects:__rw_items count:16]);
1550/// elem = nil;
1551/// __break_label: ;
1552/// }
1553/// else
1554/// elem = nil;
1555/// }
1556///
1557Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1558 SourceLocation OrigEnd) {
1559 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1560 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1561 "ObjCForCollectionStmt Statement stack mismatch");
1562 assert(!ObjCBcLabelNo.empty() &&
1563 "ObjCForCollectionStmt - Label No stack empty");
1564
1565 SourceLocation startLoc = S->getLocStart();
1566 const char *startBuf = SM->getCharacterData(startLoc);
1567 StringRef elementName;
1568 std::string elementTypeAsString;
1569 std::string buf;
1570 buf = "\n{\n\t";
1571 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1572 // type elem;
1573 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1574 QualType ElementType = cast<ValueDecl>(D)->getType();
1575 if (ElementType->isObjCQualifiedIdType() ||
1576 ElementType->isObjCQualifiedInterfaceType())
1577 // Simply use 'id' for all qualified types.
1578 elementTypeAsString = "id";
1579 else
1580 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1581 buf += elementTypeAsString;
1582 buf += " ";
1583 elementName = D->getName();
1584 buf += elementName;
1585 buf += ";\n\t";
1586 }
1587 else {
1588 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1589 elementName = DR->getDecl()->getName();
1590 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1591 if (VD->getType()->isObjCQualifiedIdType() ||
1592 VD->getType()->isObjCQualifiedInterfaceType())
1593 // Simply use 'id' for all qualified types.
1594 elementTypeAsString = "id";
1595 else
1596 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1597 }
1598
1599 // struct __objcFastEnumerationState enumState = { 0 };
1600 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1601 // id __rw_items[16];
1602 buf += "id __rw_items[16];\n\t";
1603 // id l_collection = (id)
1604 buf += "id l_collection = (id)";
1605 // Find start location of 'collection' the hard way!
1606 const char *startCollectionBuf = startBuf;
1607 startCollectionBuf += 3; // skip 'for'
1608 startCollectionBuf = strchr(startCollectionBuf, '(');
1609 startCollectionBuf++; // skip '('
1610 // find 'in' and skip it.
1611 while (*startCollectionBuf != ' ' ||
1612 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1613 (*(startCollectionBuf+3) != ' ' &&
1614 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1615 startCollectionBuf++;
1616 startCollectionBuf += 3;
1617
1618 // Replace: "for (type element in" with string constructed thus far.
1619 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1620 // Replace ')' in for '(' type elem in collection ')' with ';'
1621 SourceLocation rightParenLoc = S->getRParenLoc();
1622 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1623 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1624 buf = ";\n\t";
1625
1626 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1627 // objects:__rw_items count:16];
1628 // which is synthesized into:
1629 // unsigned int limit =
1630 // ((unsigned int (*)
1631 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1632 // (void *)objc_msgSend)((id)l_collection,
1633 // sel_registerName(
1634 // "countByEnumeratingWithState:objects:count:"),
1635 // (struct __objcFastEnumerationState *)&state,
1636 // (id *)__rw_items, (unsigned int)16);
1637 buf += "unsigned long limit =\n\t\t";
1638 SynthCountByEnumWithState(buf);
1639 buf += ";\n\t";
1640 /// if (limit) {
1641 /// unsigned long startMutations = *enumState.mutationsPtr;
1642 /// do {
1643 /// unsigned long counter = 0;
1644 /// do {
1645 /// if (startMutations != *enumState.mutationsPtr)
1646 /// objc_enumerationMutation(l_collection);
1647 /// elem = (type)enumState.itemsPtr[counter++];
1648 buf += "if (limit) {\n\t";
1649 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1650 buf += "do {\n\t\t";
1651 buf += "unsigned long counter = 0;\n\t\t";
1652 buf += "do {\n\t\t\t";
1653 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1654 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1655 buf += elementName;
1656 buf += " = (";
1657 buf += elementTypeAsString;
1658 buf += ")enumState.itemsPtr[counter++];";
1659 // Replace ')' in for '(' type elem in collection ')' with all of these.
1660 ReplaceText(lparenLoc, 1, buf);
1661
1662 /// __continue_label: ;
1663 /// } while (counter < limit);
1664 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1665 /// objects:__rw_items count:16]);
1666 /// elem = nil;
1667 /// __break_label: ;
1668 /// }
1669 /// else
1670 /// elem = nil;
1671 /// }
1672 ///
1673 buf = ";\n\t";
1674 buf += "__continue_label_";
1675 buf += utostr(ObjCBcLabelNo.back());
1676 buf += ": ;";
1677 buf += "\n\t\t";
1678 buf += "} while (counter < limit);\n\t";
1679 buf += "} while (limit = ";
1680 SynthCountByEnumWithState(buf);
1681 buf += ");\n\t";
1682 buf += elementName;
1683 buf += " = ((";
1684 buf += elementTypeAsString;
1685 buf += ")0);\n\t";
1686 buf += "__break_label_";
1687 buf += utostr(ObjCBcLabelNo.back());
1688 buf += ": ;\n\t";
1689 buf += "}\n\t";
1690 buf += "else\n\t\t";
1691 buf += elementName;
1692 buf += " = ((";
1693 buf += elementTypeAsString;
1694 buf += ")0);\n\t";
1695 buf += "}\n";
1696
1697 // Insert all these *after* the statement body.
1698 // FIXME: If this should support Obj-C++, support CXXTryStmt
1699 if (isa<CompoundStmt>(S->getBody())) {
1700 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1701 InsertText(endBodyLoc, buf);
1702 } else {
1703 /* Need to treat single statements specially. For example:
1704 *
1705 * for (A *a in b) if (stuff()) break;
1706 * for (A *a in b) xxxyy;
1707 *
1708 * The following code simply scans ahead to the semi to find the actual end.
1709 */
1710 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1711 const char *semiBuf = strchr(stmtBuf, ';');
1712 assert(semiBuf && "Can't find ';'");
1713 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1714 InsertText(endBodyLoc, buf);
1715 }
1716 Stmts.pop_back();
1717 ObjCBcLabelNo.pop_back();
1718 return 0;
1719}
1720
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001721static void Write_RethrowObject(std::string &buf) {
1722 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1723 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1724 buf += "\tid rethrow;\n";
1725 buf += "\t} _fin_force_rethow(_rethrow);";
1726}
1727
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001728/// RewriteObjCSynchronizedStmt -
1729/// This routine rewrites @synchronized(expr) stmt;
1730/// into:
1731/// objc_sync_enter(expr);
1732/// @try stmt @finally { objc_sync_exit(expr); }
1733///
1734Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1735 // Get the start location and compute the semi location.
1736 SourceLocation startLoc = S->getLocStart();
1737 const char *startBuf = SM->getCharacterData(startLoc);
1738
1739 assert((*startBuf == '@') && "bogus @synchronized location");
1740
1741 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001742 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001743
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001744 const char *lparenBuf = startBuf;
1745 while (*lparenBuf != '(') lparenBuf++;
1746 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001747
1748 buf = "; objc_sync_enter(_sync_obj);\n";
1749 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1750 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1751 buf += "\n\tid sync_exit;";
1752 buf += "\n\t} _sync_exit(_sync_obj);\n";
1753
1754 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1755 // the sync expression is typically a message expression that's already
1756 // been rewritten! (which implies the SourceLocation's are invalid).
1757 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1758 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1759 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1760 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1761
1762 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1763 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1764 assert (*LBraceLocBuf == '{');
1765 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001766
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001767 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001768 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1769 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001770
1771 buf = "} catch (id e) {_rethrow = e;}\n";
1772 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001773 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001774 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001775
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001776 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001777
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001778 return 0;
1779}
1780
1781void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1782{
1783 // Perform a bottom up traversal of all children.
1784 for (Stmt::child_range CI = S->children(); CI; ++CI)
1785 if (*CI)
1786 WarnAboutReturnGotoStmts(*CI);
1787
1788 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1789 Diags.Report(Context->getFullLoc(S->getLocStart()),
1790 TryFinallyContainsReturnDiag);
1791 }
1792 return;
1793}
1794
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001795Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001796 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001797 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001798 std::string buf;
1799
1800 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001801 if (noCatch)
1802 buf = "{ id volatile _rethrow = 0;\n";
1803 else {
1804 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1805 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001806 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001807 // Get the start location and compute the semi location.
1808 SourceLocation startLoc = S->getLocStart();
1809 const char *startBuf = SM->getCharacterData(startLoc);
1810
1811 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001812 if (finalStmt)
1813 ReplaceText(startLoc, 1, buf);
1814 else
1815 // @try -> try
1816 ReplaceText(startLoc, 1, "");
1817
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001818 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1819 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001820 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001821
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001822 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001823 bool AtRemoved = false;
1824 if (catchDecl) {
1825 QualType t = catchDecl->getType();
1826 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1827 // Should be a pointer to a class.
1828 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1829 if (IDecl) {
1830 std::string Result;
1831 startBuf = SM->getCharacterData(startLoc);
1832 assert((*startBuf == '@') && "bogus @catch location");
1833 SourceLocation rParenLoc = Catch->getRParenLoc();
1834 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1835
1836 // _objc_exc_Foo *_e as argument to catch.
1837 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1838 Result += " *_"; Result += catchDecl->getNameAsString();
1839 Result += ")";
1840 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1841 // Foo *e = (Foo *)_e;
1842 Result.clear();
1843 Result = "{ ";
1844 Result += IDecl->getNameAsString();
1845 Result += " *"; Result += catchDecl->getNameAsString();
1846 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1847 Result += "_"; Result += catchDecl->getNameAsString();
1848
1849 Result += "; ";
1850 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1851 ReplaceText(lBraceLoc, 1, Result);
1852 AtRemoved = true;
1853 }
1854 }
1855 }
1856 if (!AtRemoved)
1857 // @catch -> catch
1858 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001859
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001860 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001861 if (finalStmt) {
1862 buf.clear();
1863 if (noCatch)
1864 buf = "catch (id e) {_rethrow = e;}\n";
1865 else
1866 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1867
1868 SourceLocation startFinalLoc = finalStmt->getLocStart();
1869 ReplaceText(startFinalLoc, 8, buf);
1870 Stmt *body = finalStmt->getFinallyBody();
1871 SourceLocation startFinalBodyLoc = body->getLocStart();
1872 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001873 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001874 ReplaceText(startFinalBodyLoc, 1, buf);
1875
1876 SourceLocation endFinalBodyLoc = body->getLocEnd();
1877 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001878 // Now check for any return/continue/go statements within the @try.
1879 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001880 }
1881
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001882 return 0;
1883}
1884
1885// This can't be done with ReplaceStmt(S, ThrowExpr), since
1886// the throw expression is typically a message expression that's already
1887// been rewritten! (which implies the SourceLocation's are invalid).
1888Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1889 // Get the start location and compute the semi location.
1890 SourceLocation startLoc = S->getLocStart();
1891 const char *startBuf = SM->getCharacterData(startLoc);
1892
1893 assert((*startBuf == '@') && "bogus @throw location");
1894
1895 std::string buf;
1896 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1897 if (S->getThrowExpr())
1898 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001899 else
1900 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001901
1902 // handle "@ throw" correctly.
1903 const char *wBuf = strchr(startBuf, 'w');
1904 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1905 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1906
1907 const char *semiBuf = strchr(startBuf, ';');
1908 assert((*semiBuf == ';') && "@throw: can't find ';'");
1909 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001910 if (S->getThrowExpr())
1911 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001912 return 0;
1913}
1914
1915Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1916 // Create a new string expression.
1917 QualType StrType = Context->getPointerType(Context->CharTy);
1918 std::string StrEncoding;
1919 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1920 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1921 StringLiteral::Ascii, false,
1922 StrType, SourceLocation());
1923 ReplaceStmt(Exp, Replacement);
1924
1925 // Replace this subexpr in the parent.
1926 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1927 return Replacement;
1928}
1929
1930Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1931 if (!SelGetUidFunctionDecl)
1932 SynthSelGetUidFunctionDecl();
1933 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1934 // Create a call to sel_registerName("selName").
1935 SmallVector<Expr*, 8> SelExprs;
1936 QualType argType = Context->getPointerType(Context->CharTy);
1937 SelExprs.push_back(StringLiteral::Create(*Context,
1938 Exp->getSelector().getAsString(),
1939 StringLiteral::Ascii, false,
1940 argType, SourceLocation()));
1941 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1942 &SelExprs[0], SelExprs.size());
1943 ReplaceStmt(Exp, SelExp);
1944 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1945 return SelExp;
1946}
1947
1948CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1949 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1950 SourceLocation EndLoc) {
1951 // Get the type, we will need to reference it in a couple spots.
1952 QualType msgSendType = FD->getType();
1953
1954 // Create a reference to the objc_msgSend() declaration.
1955 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001956 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001957
1958 // Now, we cast the reference to a pointer to the objc_msgSend type.
1959 QualType pToFunc = Context->getPointerType(msgSendType);
1960 ImplicitCastExpr *ICE =
1961 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1962 DRE, 0, VK_RValue);
1963
1964 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1965
1966 CallExpr *Exp =
1967 new (Context) CallExpr(*Context, ICE, args, nargs,
1968 FT->getCallResultType(*Context),
1969 VK_RValue, EndLoc);
1970 return Exp;
1971}
1972
1973static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1974 const char *&startRef, const char *&endRef) {
1975 while (startBuf < endBuf) {
1976 if (*startBuf == '<')
1977 startRef = startBuf; // mark the start.
1978 if (*startBuf == '>') {
1979 if (startRef && *startRef == '<') {
1980 endRef = startBuf; // mark the end.
1981 return true;
1982 }
1983 return false;
1984 }
1985 startBuf++;
1986 }
1987 return false;
1988}
1989
1990static void scanToNextArgument(const char *&argRef) {
1991 int angle = 0;
1992 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1993 if (*argRef == '<')
1994 angle++;
1995 else if (*argRef == '>')
1996 angle--;
1997 argRef++;
1998 }
1999 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2000}
2001
2002bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2003 if (T->isObjCQualifiedIdType())
2004 return true;
2005 if (const PointerType *PT = T->getAs<PointerType>()) {
2006 if (PT->getPointeeType()->isObjCQualifiedIdType())
2007 return true;
2008 }
2009 if (T->isObjCObjectPointerType()) {
2010 T = T->getPointeeType();
2011 return T->isObjCQualifiedInterfaceType();
2012 }
2013 if (T->isArrayType()) {
2014 QualType ElemTy = Context->getBaseElementType(T);
2015 return needToScanForQualifiers(ElemTy);
2016 }
2017 return false;
2018}
2019
2020void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2021 QualType Type = E->getType();
2022 if (needToScanForQualifiers(Type)) {
2023 SourceLocation Loc, EndLoc;
2024
2025 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2026 Loc = ECE->getLParenLoc();
2027 EndLoc = ECE->getRParenLoc();
2028 } else {
2029 Loc = E->getLocStart();
2030 EndLoc = E->getLocEnd();
2031 }
2032 // This will defend against trying to rewrite synthesized expressions.
2033 if (Loc.isInvalid() || EndLoc.isInvalid())
2034 return;
2035
2036 const char *startBuf = SM->getCharacterData(Loc);
2037 const char *endBuf = SM->getCharacterData(EndLoc);
2038 const char *startRef = 0, *endRef = 0;
2039 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2040 // Get the locations of the startRef, endRef.
2041 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2042 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2043 // Comment out the protocol references.
2044 InsertText(LessLoc, "/*");
2045 InsertText(GreaterLoc, "*/");
2046 }
2047 }
2048}
2049
2050void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2051 SourceLocation Loc;
2052 QualType Type;
2053 const FunctionProtoType *proto = 0;
2054 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2055 Loc = VD->getLocation();
2056 Type = VD->getType();
2057 }
2058 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2059 Loc = FD->getLocation();
2060 // Check for ObjC 'id' and class types that have been adorned with protocol
2061 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2062 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2063 assert(funcType && "missing function type");
2064 proto = dyn_cast<FunctionProtoType>(funcType);
2065 if (!proto)
2066 return;
2067 Type = proto->getResultType();
2068 }
2069 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2070 Loc = FD->getLocation();
2071 Type = FD->getType();
2072 }
2073 else
2074 return;
2075
2076 if (needToScanForQualifiers(Type)) {
2077 // Since types are unique, we need to scan the buffer.
2078
2079 const char *endBuf = SM->getCharacterData(Loc);
2080 const char *startBuf = endBuf;
2081 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2082 startBuf--; // scan backward (from the decl location) for return type.
2083 const char *startRef = 0, *endRef = 0;
2084 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2085 // Get the locations of the startRef, endRef.
2086 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2087 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2088 // Comment out the protocol references.
2089 InsertText(LessLoc, "/*");
2090 InsertText(GreaterLoc, "*/");
2091 }
2092 }
2093 if (!proto)
2094 return; // most likely, was a variable
2095 // Now check arguments.
2096 const char *startBuf = SM->getCharacterData(Loc);
2097 const char *startFuncBuf = startBuf;
2098 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2099 if (needToScanForQualifiers(proto->getArgType(i))) {
2100 // Since types are unique, we need to scan the buffer.
2101
2102 const char *endBuf = startBuf;
2103 // scan forward (from the decl location) for argument types.
2104 scanToNextArgument(endBuf);
2105 const char *startRef = 0, *endRef = 0;
2106 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2107 // Get the locations of the startRef, endRef.
2108 SourceLocation LessLoc =
2109 Loc.getLocWithOffset(startRef-startFuncBuf);
2110 SourceLocation GreaterLoc =
2111 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2112 // Comment out the protocol references.
2113 InsertText(LessLoc, "/*");
2114 InsertText(GreaterLoc, "*/");
2115 }
2116 startBuf = ++endBuf;
2117 }
2118 else {
2119 // If the function name is derived from a macro expansion, then the
2120 // argument buffer will not follow the name. Need to speak with Chris.
2121 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2122 startBuf++; // scan forward (from the decl location) for argument types.
2123 startBuf++;
2124 }
2125 }
2126}
2127
2128void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2129 QualType QT = ND->getType();
2130 const Type* TypePtr = QT->getAs<Type>();
2131 if (!isa<TypeOfExprType>(TypePtr))
2132 return;
2133 while (isa<TypeOfExprType>(TypePtr)) {
2134 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2135 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2136 TypePtr = QT->getAs<Type>();
2137 }
2138 // FIXME. This will not work for multiple declarators; as in:
2139 // __typeof__(a) b,c,d;
2140 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2141 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2142 const char *startBuf = SM->getCharacterData(DeclLoc);
2143 if (ND->getInit()) {
2144 std::string Name(ND->getNameAsString());
2145 TypeAsString += " " + Name + " = ";
2146 Expr *E = ND->getInit();
2147 SourceLocation startLoc;
2148 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2149 startLoc = ECE->getLParenLoc();
2150 else
2151 startLoc = E->getLocStart();
2152 startLoc = SM->getExpansionLoc(startLoc);
2153 const char *endBuf = SM->getCharacterData(startLoc);
2154 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2155 }
2156 else {
2157 SourceLocation X = ND->getLocEnd();
2158 X = SM->getExpansionLoc(X);
2159 const char *endBuf = SM->getCharacterData(X);
2160 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2161 }
2162}
2163
2164// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2165void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2166 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2167 SmallVector<QualType, 16> ArgTys;
2168 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2169 QualType getFuncType =
2170 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2171 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2172 SourceLocation(),
2173 SourceLocation(),
2174 SelGetUidIdent, getFuncType, 0,
2175 SC_Extern,
2176 SC_None, false);
2177}
2178
2179void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2180 // declared in <objc/objc.h>
2181 if (FD->getIdentifier() &&
2182 FD->getName() == "sel_registerName") {
2183 SelGetUidFunctionDecl = FD;
2184 return;
2185 }
2186 RewriteObjCQualifiedInterfaceTypes(FD);
2187}
2188
2189void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2190 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2191 const char *argPtr = TypeString.c_str();
2192 if (!strchr(argPtr, '^')) {
2193 Str += TypeString;
2194 return;
2195 }
2196 while (*argPtr) {
2197 Str += (*argPtr == '^' ? '*' : *argPtr);
2198 argPtr++;
2199 }
2200}
2201
2202// FIXME. Consolidate this routine with RewriteBlockPointerType.
2203void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2204 ValueDecl *VD) {
2205 QualType Type = VD->getType();
2206 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2207 const char *argPtr = TypeString.c_str();
2208 int paren = 0;
2209 while (*argPtr) {
2210 switch (*argPtr) {
2211 case '(':
2212 Str += *argPtr;
2213 paren++;
2214 break;
2215 case ')':
2216 Str += *argPtr;
2217 paren--;
2218 break;
2219 case '^':
2220 Str += '*';
2221 if (paren == 1)
2222 Str += VD->getNameAsString();
2223 break;
2224 default:
2225 Str += *argPtr;
2226 break;
2227 }
2228 argPtr++;
2229 }
2230}
2231
2232
2233void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2234 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2235 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2236 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2237 if (!proto)
2238 return;
2239 QualType Type = proto->getResultType();
2240 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2241 FdStr += " ";
2242 FdStr += FD->getName();
2243 FdStr += "(";
2244 unsigned numArgs = proto->getNumArgs();
2245 for (unsigned i = 0; i < numArgs; i++) {
2246 QualType ArgType = proto->getArgType(i);
2247 RewriteBlockPointerType(FdStr, ArgType);
2248 if (i+1 < numArgs)
2249 FdStr += ", ";
2250 }
2251 FdStr += ");\n";
2252 InsertText(FunLocStart, FdStr);
2253 CurFunctionDeclToDeclareForBlock = 0;
2254}
2255
2256// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2257void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2258 if (SuperContructorFunctionDecl)
2259 return;
2260 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2261 SmallVector<QualType, 16> ArgTys;
2262 QualType argT = Context->getObjCIdType();
2263 assert(!argT.isNull() && "Can't find 'id' type");
2264 ArgTys.push_back(argT);
2265 ArgTys.push_back(argT);
2266 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2267 &ArgTys[0], ArgTys.size());
2268 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2269 SourceLocation(),
2270 SourceLocation(),
2271 msgSendIdent, msgSendType, 0,
2272 SC_Extern,
2273 SC_None, false);
2274}
2275
2276// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2277void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2278 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2279 SmallVector<QualType, 16> ArgTys;
2280 QualType argT = Context->getObjCIdType();
2281 assert(!argT.isNull() && "Can't find 'id' type");
2282 ArgTys.push_back(argT);
2283 argT = Context->getObjCSelType();
2284 assert(!argT.isNull() && "Can't find 'SEL' type");
2285 ArgTys.push_back(argT);
2286 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2287 &ArgTys[0], ArgTys.size(),
2288 true /*isVariadic*/);
2289 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2290 SourceLocation(),
2291 SourceLocation(),
2292 msgSendIdent, msgSendType, 0,
2293 SC_Extern,
2294 SC_None, false);
2295}
2296
2297// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2298void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2299 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2300 SmallVector<QualType, 16> ArgTys;
2301 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2302 SourceLocation(), SourceLocation(),
2303 &Context->Idents.get("objc_super"));
2304 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2305 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2306 ArgTys.push_back(argT);
2307 argT = Context->getObjCSelType();
2308 assert(!argT.isNull() && "Can't find 'SEL' type");
2309 ArgTys.push_back(argT);
2310 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2311 &ArgTys[0], ArgTys.size(),
2312 true /*isVariadic*/);
2313 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2314 SourceLocation(),
2315 SourceLocation(),
2316 msgSendIdent, msgSendType, 0,
2317 SC_Extern,
2318 SC_None, false);
2319}
2320
2321// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2322void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2323 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2324 SmallVector<QualType, 16> ArgTys;
2325 QualType argT = Context->getObjCIdType();
2326 assert(!argT.isNull() && "Can't find 'id' type");
2327 ArgTys.push_back(argT);
2328 argT = Context->getObjCSelType();
2329 assert(!argT.isNull() && "Can't find 'SEL' type");
2330 ArgTys.push_back(argT);
2331 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2332 &ArgTys[0], ArgTys.size(),
2333 true /*isVariadic*/);
2334 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2335 SourceLocation(),
2336 SourceLocation(),
2337 msgSendIdent, msgSendType, 0,
2338 SC_Extern,
2339 SC_None, false);
2340}
2341
2342// SynthMsgSendSuperStretFunctionDecl -
2343// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2344void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2345 IdentifierInfo *msgSendIdent =
2346 &Context->Idents.get("objc_msgSendSuper_stret");
2347 SmallVector<QualType, 16> ArgTys;
2348 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2349 SourceLocation(), SourceLocation(),
2350 &Context->Idents.get("objc_super"));
2351 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2352 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2353 ArgTys.push_back(argT);
2354 argT = Context->getObjCSelType();
2355 assert(!argT.isNull() && "Can't find 'SEL' type");
2356 ArgTys.push_back(argT);
2357 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2358 &ArgTys[0], ArgTys.size(),
2359 true /*isVariadic*/);
2360 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2361 SourceLocation(),
2362 SourceLocation(),
2363 msgSendIdent, msgSendType, 0,
2364 SC_Extern,
2365 SC_None, false);
2366}
2367
2368// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2369void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2370 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2371 SmallVector<QualType, 16> ArgTys;
2372 QualType argT = Context->getObjCIdType();
2373 assert(!argT.isNull() && "Can't find 'id' type");
2374 ArgTys.push_back(argT);
2375 argT = Context->getObjCSelType();
2376 assert(!argT.isNull() && "Can't find 'SEL' type");
2377 ArgTys.push_back(argT);
2378 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2379 &ArgTys[0], ArgTys.size(),
2380 true /*isVariadic*/);
2381 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2382 SourceLocation(),
2383 SourceLocation(),
2384 msgSendIdent, msgSendType, 0,
2385 SC_Extern,
2386 SC_None, false);
2387}
2388
2389// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2390void RewriteModernObjC::SynthGetClassFunctionDecl() {
2391 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2392 SmallVector<QualType, 16> ArgTys;
2393 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2394 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2395 &ArgTys[0], ArgTys.size());
2396 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2397 SourceLocation(),
2398 SourceLocation(),
2399 getClassIdent, getClassType, 0,
2400 SC_Extern,
2401 SC_None, false);
2402}
2403
2404// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2405void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2406 IdentifierInfo *getSuperClassIdent =
2407 &Context->Idents.get("class_getSuperclass");
2408 SmallVector<QualType, 16> ArgTys;
2409 ArgTys.push_back(Context->getObjCClassType());
2410 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2411 &ArgTys[0], ArgTys.size());
2412 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2413 SourceLocation(),
2414 SourceLocation(),
2415 getSuperClassIdent,
2416 getClassType, 0,
2417 SC_Extern,
2418 SC_None,
2419 false);
2420}
2421
2422// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2423void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2424 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2425 SmallVector<QualType, 16> ArgTys;
2426 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2427 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2428 &ArgTys[0], ArgTys.size());
2429 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2430 SourceLocation(),
2431 SourceLocation(),
2432 getClassIdent, getClassType, 0,
2433 SC_Extern,
2434 SC_None, false);
2435}
2436
2437Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2438 QualType strType = getConstantStringStructType();
2439
2440 std::string S = "__NSConstantStringImpl_";
2441
2442 std::string tmpName = InFileName;
2443 unsigned i;
2444 for (i=0; i < tmpName.length(); i++) {
2445 char c = tmpName.at(i);
2446 // replace any non alphanumeric characters with '_'.
2447 if (!isalpha(c) && (c < '0' || c > '9'))
2448 tmpName[i] = '_';
2449 }
2450 S += tmpName;
2451 S += "_";
2452 S += utostr(NumObjCStringLiterals++);
2453
2454 Preamble += "static __NSConstantStringImpl " + S;
2455 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2456 Preamble += "0x000007c8,"; // utf8_str
2457 // The pretty printer for StringLiteral handles escape characters properly.
2458 std::string prettyBufS;
2459 llvm::raw_string_ostream prettyBuf(prettyBufS);
2460 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2461 PrintingPolicy(LangOpts));
2462 Preamble += prettyBuf.str();
2463 Preamble += ",";
2464 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2465
2466 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2467 SourceLocation(), &Context->Idents.get(S),
2468 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002469 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002470 SourceLocation());
2471 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2472 Context->getPointerType(DRE->getType()),
2473 VK_RValue, OK_Ordinary,
2474 SourceLocation());
2475 // cast to NSConstantString *
2476 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2477 CK_CPointerToObjCPointerCast, Unop);
2478 ReplaceStmt(Exp, cast);
2479 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2480 return cast;
2481}
2482
Fariborz Jahanian55947042012-03-27 20:17:30 +00002483Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2484 unsigned IntSize =
2485 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2486
2487 Expr *FlagExp = IntegerLiteral::Create(*Context,
2488 llvm::APInt(IntSize, Exp->getValue()),
2489 Context->IntTy, Exp->getLocation());
2490 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2491 CK_BitCast, FlagExp);
2492 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2493 cast);
2494 ReplaceStmt(Exp, PE);
2495 return PE;
2496}
2497
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002498Stmt *RewriteModernObjC::RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp) {
2499 // synthesize declaration of helper functions needed in this routine.
2500 if (!SelGetUidFunctionDecl)
2501 SynthSelGetUidFunctionDecl();
2502 // use objc_msgSend() for all.
2503 if (!MsgSendFunctionDecl)
2504 SynthMsgSendFunctionDecl();
2505 if (!GetClassFunctionDecl)
2506 SynthGetClassFunctionDecl();
2507
2508 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2509 SourceLocation StartLoc = Exp->getLocStart();
2510 SourceLocation EndLoc = Exp->getLocEnd();
2511
2512 // Synthesize a call to objc_msgSend().
2513 SmallVector<Expr*, 4> MsgExprs;
2514 SmallVector<Expr*, 4> ClsExprs;
2515 QualType argType = Context->getPointerType(Context->CharTy);
2516 QualType expType = Exp->getType();
2517
2518 // Create a call to objc_getClass("NSNumber"). It will be th 1st argument.
2519 ObjCInterfaceDecl *Class =
2520 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2521
2522 IdentifierInfo *clsName = Class->getIdentifier();
2523 ClsExprs.push_back(StringLiteral::Create(*Context,
2524 clsName->getName(),
2525 StringLiteral::Ascii, false,
2526 argType, SourceLocation()));
2527 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2528 &ClsExprs[0],
2529 ClsExprs.size(),
2530 StartLoc, EndLoc);
2531 MsgExprs.push_back(Cls);
2532
2533 // Create a call to sel_registerName("numberWithBool:"), etc.
2534 // it will be the 2nd argument.
2535 SmallVector<Expr*, 4> SelExprs;
2536 ObjCMethodDecl *NumericMethod = Exp->getObjCNumericLiteralMethod();
2537 SelExprs.push_back(StringLiteral::Create(*Context,
2538 NumericMethod->getSelector().getAsString(),
2539 StringLiteral::Ascii, false,
2540 argType, SourceLocation()));
2541 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2542 &SelExprs[0], SelExprs.size(),
2543 StartLoc, EndLoc);
2544 MsgExprs.push_back(SelExp);
2545
2546 // User provided numeric literal is the 3rd, and last, argument.
2547 Expr *userExpr = Exp->getNumber();
2548 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2549 QualType type = ICE->getType();
2550 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2551 CastKind CK = CK_BitCast;
2552 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2553 CK = CK_IntegralToBoolean;
2554 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2555 }
2556 MsgExprs.push_back(userExpr);
2557
2558 SmallVector<QualType, 4> ArgTypes;
2559 ArgTypes.push_back(Context->getObjCIdType());
2560 ArgTypes.push_back(Context->getObjCSelType());
2561 for (ObjCMethodDecl::param_iterator PI = NumericMethod->param_begin(),
2562 E = NumericMethod->param_end(); PI != E; ++PI)
2563 ArgTypes.push_back((*PI)->getType());
2564
2565 QualType returnType = Exp->getType();
2566 // Get the type, we will need to reference it in a couple spots.
2567 QualType msgSendType = MsgSendFlavor->getType();
2568
2569 // Create a reference to the objc_msgSend() declaration.
2570 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2571 VK_LValue, SourceLocation());
2572
2573 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2574 Context->getPointerType(Context->VoidTy),
2575 CK_BitCast, DRE);
2576
2577 // Now do the "normal" pointer to function cast.
2578 QualType castType =
2579 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2580 NumericMethod->isVariadic());
2581 castType = Context->getPointerType(castType);
2582 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2583 cast);
2584
2585 // Don't forget the parens to enforce the proper binding.
2586 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2587
2588 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2589 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2590 MsgExprs.size(),
2591 FT->getResultType(), VK_RValue,
2592 EndLoc);
2593 ReplaceStmt(Exp, CE);
2594 return CE;
2595}
2596
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002597Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2598 // synthesize declaration of helper functions needed in this routine.
2599 if (!SelGetUidFunctionDecl)
2600 SynthSelGetUidFunctionDecl();
2601 // use objc_msgSend() for all.
2602 if (!MsgSendFunctionDecl)
2603 SynthMsgSendFunctionDecl();
2604 if (!GetClassFunctionDecl)
2605 SynthGetClassFunctionDecl();
2606
2607 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2608 SourceLocation StartLoc = Exp->getLocStart();
2609 SourceLocation EndLoc = Exp->getLocEnd();
2610
2611 // Synthesize a call to objc_msgSend().
2612 SmallVector<Expr*, 32> MsgExprs;
2613 SmallVector<Expr*, 4> ClsExprs;
2614 QualType argType = Context->getPointerType(Context->CharTy);
2615 QualType expType = Exp->getType();
2616
2617 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2618 ObjCInterfaceDecl *Class =
2619 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2620
2621 IdentifierInfo *clsName = Class->getIdentifier();
2622 ClsExprs.push_back(StringLiteral::Create(*Context,
2623 clsName->getName(),
2624 StringLiteral::Ascii, false,
2625 argType, SourceLocation()));
2626 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2627 &ClsExprs[0],
2628 ClsExprs.size(),
2629 StartLoc, EndLoc);
2630 MsgExprs.push_back(Cls);
2631
2632 // Create a call to sel_registerName("arrayWithObjects:count:").
2633 // it will be the 2nd argument.
2634 SmallVector<Expr*, 4> SelExprs;
2635 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2636 SelExprs.push_back(StringLiteral::Create(*Context,
2637 ArrayMethod->getSelector().getAsString(),
2638 StringLiteral::Ascii, false,
2639 argType, SourceLocation()));
2640 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2641 &SelExprs[0], SelExprs.size(),
2642 StartLoc, EndLoc);
2643 MsgExprs.push_back(SelExp);
2644
2645 unsigned NumElements = Exp->getNumElements();
2646
2647 // FIXME. Incomplete.
2648 InitListExpr *ILE =
2649 new (Context) InitListExpr(*Context, SourceLocation(),
2650 Exp->getElements(), NumElements,
2651 SourceLocation());
2652 MsgExprs.push_back(ILE);
2653 unsigned UnsignedIntSize =
2654 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2655
2656 Expr *count = IntegerLiteral::Create(*Context,
2657 llvm::APInt(UnsignedIntSize, NumElements),
2658 Context->UnsignedIntTy,
2659 SourceLocation());
2660 MsgExprs.push_back(count);
2661
2662
2663 SmallVector<QualType, 4> ArgTypes;
2664 ArgTypes.push_back(Context->getObjCIdType());
2665 ArgTypes.push_back(Context->getObjCSelType());
2666 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2667 E = ArrayMethod->param_end(); PI != E; ++PI)
2668 ArgTypes.push_back((*PI)->getType());
2669
2670 QualType returnType = Exp->getType();
2671 // Get the type, we will need to reference it in a couple spots.
2672 QualType msgSendType = MsgSendFlavor->getType();
2673
2674 // Create a reference to the objc_msgSend() declaration.
2675 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2676 VK_LValue, SourceLocation());
2677
2678 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2679 Context->getPointerType(Context->VoidTy),
2680 CK_BitCast, DRE);
2681
2682 // Now do the "normal" pointer to function cast.
2683 QualType castType =
2684 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2685 ArrayMethod->isVariadic());
2686 castType = Context->getPointerType(castType);
2687 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2688 cast);
2689
2690 // Don't forget the parens to enforce the proper binding.
2691 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2692
2693 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2694 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2695 MsgExprs.size(),
2696 FT->getResultType(), VK_RValue,
2697 EndLoc);
2698 ReplaceStmt(Exp, CE);
2699 return CE;
2700}
2701
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002702// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2703QualType RewriteModernObjC::getSuperStructType() {
2704 if (!SuperStructDecl) {
2705 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2706 SourceLocation(), SourceLocation(),
2707 &Context->Idents.get("objc_super"));
2708 QualType FieldTypes[2];
2709
2710 // struct objc_object *receiver;
2711 FieldTypes[0] = Context->getObjCIdType();
2712 // struct objc_class *super;
2713 FieldTypes[1] = Context->getObjCClassType();
2714
2715 // Create fields
2716 for (unsigned i = 0; i < 2; ++i) {
2717 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2718 SourceLocation(),
2719 SourceLocation(), 0,
2720 FieldTypes[i], 0,
2721 /*BitWidth=*/0,
2722 /*Mutable=*/false,
2723 /*HasInit=*/false));
2724 }
2725
2726 SuperStructDecl->completeDefinition();
2727 }
2728 return Context->getTagDeclType(SuperStructDecl);
2729}
2730
2731QualType RewriteModernObjC::getConstantStringStructType() {
2732 if (!ConstantStringDecl) {
2733 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2734 SourceLocation(), SourceLocation(),
2735 &Context->Idents.get("__NSConstantStringImpl"));
2736 QualType FieldTypes[4];
2737
2738 // struct objc_object *receiver;
2739 FieldTypes[0] = Context->getObjCIdType();
2740 // int flags;
2741 FieldTypes[1] = Context->IntTy;
2742 // char *str;
2743 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2744 // long length;
2745 FieldTypes[3] = Context->LongTy;
2746
2747 // Create fields
2748 for (unsigned i = 0; i < 4; ++i) {
2749 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2750 ConstantStringDecl,
2751 SourceLocation(),
2752 SourceLocation(), 0,
2753 FieldTypes[i], 0,
2754 /*BitWidth=*/0,
2755 /*Mutable=*/true,
2756 /*HasInit=*/false));
2757 }
2758
2759 ConstantStringDecl->completeDefinition();
2760 }
2761 return Context->getTagDeclType(ConstantStringDecl);
2762}
2763
2764Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2765 SourceLocation StartLoc,
2766 SourceLocation EndLoc) {
2767 if (!SelGetUidFunctionDecl)
2768 SynthSelGetUidFunctionDecl();
2769 if (!MsgSendFunctionDecl)
2770 SynthMsgSendFunctionDecl();
2771 if (!MsgSendSuperFunctionDecl)
2772 SynthMsgSendSuperFunctionDecl();
2773 if (!MsgSendStretFunctionDecl)
2774 SynthMsgSendStretFunctionDecl();
2775 if (!MsgSendSuperStretFunctionDecl)
2776 SynthMsgSendSuperStretFunctionDecl();
2777 if (!MsgSendFpretFunctionDecl)
2778 SynthMsgSendFpretFunctionDecl();
2779 if (!GetClassFunctionDecl)
2780 SynthGetClassFunctionDecl();
2781 if (!GetSuperClassFunctionDecl)
2782 SynthGetSuperClassFunctionDecl();
2783 if (!GetMetaClassFunctionDecl)
2784 SynthGetMetaClassFunctionDecl();
2785
2786 // default to objc_msgSend().
2787 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2788 // May need to use objc_msgSend_stret() as well.
2789 FunctionDecl *MsgSendStretFlavor = 0;
2790 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2791 QualType resultType = mDecl->getResultType();
2792 if (resultType->isRecordType())
2793 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2794 else if (resultType->isRealFloatingType())
2795 MsgSendFlavor = MsgSendFpretFunctionDecl;
2796 }
2797
2798 // Synthesize a call to objc_msgSend().
2799 SmallVector<Expr*, 8> MsgExprs;
2800 switch (Exp->getReceiverKind()) {
2801 case ObjCMessageExpr::SuperClass: {
2802 MsgSendFlavor = MsgSendSuperFunctionDecl;
2803 if (MsgSendStretFlavor)
2804 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2805 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2806
2807 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2808
2809 SmallVector<Expr*, 4> InitExprs;
2810
2811 // set the receiver to self, the first argument to all methods.
2812 InitExprs.push_back(
2813 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2814 CK_BitCast,
2815 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002816 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002817 Context->getObjCIdType(),
2818 VK_RValue,
2819 SourceLocation()))
2820 ); // set the 'receiver'.
2821
2822 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2823 SmallVector<Expr*, 8> ClsExprs;
2824 QualType argType = Context->getPointerType(Context->CharTy);
2825 ClsExprs.push_back(StringLiteral::Create(*Context,
2826 ClassDecl->getIdentifier()->getName(),
2827 StringLiteral::Ascii, false,
2828 argType, SourceLocation()));
2829 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2830 &ClsExprs[0],
2831 ClsExprs.size(),
2832 StartLoc,
2833 EndLoc);
2834 // (Class)objc_getClass("CurrentClass")
2835 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2836 Context->getObjCClassType(),
2837 CK_BitCast, Cls);
2838 ClsExprs.clear();
2839 ClsExprs.push_back(ArgExpr);
2840 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2841 &ClsExprs[0], ClsExprs.size(),
2842 StartLoc, EndLoc);
2843
2844 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2845 // To turn off a warning, type-cast to 'id'
2846 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2847 NoTypeInfoCStyleCastExpr(Context,
2848 Context->getObjCIdType(),
2849 CK_BitCast, Cls));
2850 // struct objc_super
2851 QualType superType = getSuperStructType();
2852 Expr *SuperRep;
2853
2854 if (LangOpts.MicrosoftExt) {
2855 SynthSuperContructorFunctionDecl();
2856 // Simulate a contructor call...
2857 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002858 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002859 SourceLocation());
2860 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2861 InitExprs.size(),
2862 superType, VK_LValue,
2863 SourceLocation());
2864 // The code for super is a little tricky to prevent collision with
2865 // the structure definition in the header. The rewriter has it's own
2866 // internal definition (__rw_objc_super) that is uses. This is why
2867 // we need the cast below. For example:
2868 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2869 //
2870 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2871 Context->getPointerType(SuperRep->getType()),
2872 VK_RValue, OK_Ordinary,
2873 SourceLocation());
2874 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2875 Context->getPointerType(superType),
2876 CK_BitCast, SuperRep);
2877 } else {
2878 // (struct objc_super) { <exprs from above> }
2879 InitListExpr *ILE =
2880 new (Context) InitListExpr(*Context, SourceLocation(),
2881 &InitExprs[0], InitExprs.size(),
2882 SourceLocation());
2883 TypeSourceInfo *superTInfo
2884 = Context->getTrivialTypeSourceInfo(superType);
2885 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2886 superType, VK_LValue,
2887 ILE, false);
2888 // struct objc_super *
2889 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2890 Context->getPointerType(SuperRep->getType()),
2891 VK_RValue, OK_Ordinary,
2892 SourceLocation());
2893 }
2894 MsgExprs.push_back(SuperRep);
2895 break;
2896 }
2897
2898 case ObjCMessageExpr::Class: {
2899 SmallVector<Expr*, 8> ClsExprs;
2900 QualType argType = Context->getPointerType(Context->CharTy);
2901 ObjCInterfaceDecl *Class
2902 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2903 IdentifierInfo *clsName = Class->getIdentifier();
2904 ClsExprs.push_back(StringLiteral::Create(*Context,
2905 clsName->getName(),
2906 StringLiteral::Ascii, false,
2907 argType, SourceLocation()));
2908 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2909 &ClsExprs[0],
2910 ClsExprs.size(),
2911 StartLoc, EndLoc);
2912 MsgExprs.push_back(Cls);
2913 break;
2914 }
2915
2916 case ObjCMessageExpr::SuperInstance:{
2917 MsgSendFlavor = MsgSendSuperFunctionDecl;
2918 if (MsgSendStretFlavor)
2919 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2920 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2921 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2922 SmallVector<Expr*, 4> InitExprs;
2923
2924 InitExprs.push_back(
2925 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2926 CK_BitCast,
2927 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002928 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002929 Context->getObjCIdType(),
2930 VK_RValue, SourceLocation()))
2931 ); // set the 'receiver'.
2932
2933 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2934 SmallVector<Expr*, 8> ClsExprs;
2935 QualType argType = Context->getPointerType(Context->CharTy);
2936 ClsExprs.push_back(StringLiteral::Create(*Context,
2937 ClassDecl->getIdentifier()->getName(),
2938 StringLiteral::Ascii, false, argType,
2939 SourceLocation()));
2940 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2941 &ClsExprs[0],
2942 ClsExprs.size(),
2943 StartLoc, EndLoc);
2944 // (Class)objc_getClass("CurrentClass")
2945 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2946 Context->getObjCClassType(),
2947 CK_BitCast, Cls);
2948 ClsExprs.clear();
2949 ClsExprs.push_back(ArgExpr);
2950 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2951 &ClsExprs[0], ClsExprs.size(),
2952 StartLoc, EndLoc);
2953
2954 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2955 // To turn off a warning, type-cast to 'id'
2956 InitExprs.push_back(
2957 // set 'super class', using class_getSuperclass().
2958 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2959 CK_BitCast, Cls));
2960 // struct objc_super
2961 QualType superType = getSuperStructType();
2962 Expr *SuperRep;
2963
2964 if (LangOpts.MicrosoftExt) {
2965 SynthSuperContructorFunctionDecl();
2966 // Simulate a contructor call...
2967 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002968 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002969 SourceLocation());
2970 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2971 InitExprs.size(),
2972 superType, VK_LValue, SourceLocation());
2973 // The code for super is a little tricky to prevent collision with
2974 // the structure definition in the header. The rewriter has it's own
2975 // internal definition (__rw_objc_super) that is uses. This is why
2976 // we need the cast below. For example:
2977 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2978 //
2979 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2980 Context->getPointerType(SuperRep->getType()),
2981 VK_RValue, OK_Ordinary,
2982 SourceLocation());
2983 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2984 Context->getPointerType(superType),
2985 CK_BitCast, SuperRep);
2986 } else {
2987 // (struct objc_super) { <exprs from above> }
2988 InitListExpr *ILE =
2989 new (Context) InitListExpr(*Context, SourceLocation(),
2990 &InitExprs[0], InitExprs.size(),
2991 SourceLocation());
2992 TypeSourceInfo *superTInfo
2993 = Context->getTrivialTypeSourceInfo(superType);
2994 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2995 superType, VK_RValue, ILE,
2996 false);
2997 }
2998 MsgExprs.push_back(SuperRep);
2999 break;
3000 }
3001
3002 case ObjCMessageExpr::Instance: {
3003 // Remove all type-casts because it may contain objc-style types; e.g.
3004 // Foo<Proto> *.
3005 Expr *recExpr = Exp->getInstanceReceiver();
3006 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3007 recExpr = CE->getSubExpr();
3008 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3009 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3010 ? CK_BlockPointerToObjCPointerCast
3011 : CK_CPointerToObjCPointerCast;
3012
3013 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3014 CK, recExpr);
3015 MsgExprs.push_back(recExpr);
3016 break;
3017 }
3018 }
3019
3020 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3021 SmallVector<Expr*, 8> SelExprs;
3022 QualType argType = Context->getPointerType(Context->CharTy);
3023 SelExprs.push_back(StringLiteral::Create(*Context,
3024 Exp->getSelector().getAsString(),
3025 StringLiteral::Ascii, false,
3026 argType, SourceLocation()));
3027 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3028 &SelExprs[0], SelExprs.size(),
3029 StartLoc,
3030 EndLoc);
3031 MsgExprs.push_back(SelExp);
3032
3033 // Now push any user supplied arguments.
3034 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3035 Expr *userExpr = Exp->getArg(i);
3036 // Make all implicit casts explicit...ICE comes in handy:-)
3037 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3038 // Reuse the ICE type, it is exactly what the doctor ordered.
3039 QualType type = ICE->getType();
3040 if (needToScanForQualifiers(type))
3041 type = Context->getObjCIdType();
3042 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3043 (void)convertBlockPointerToFunctionPointer(type);
3044 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3045 CastKind CK;
3046 if (SubExpr->getType()->isIntegralType(*Context) &&
3047 type->isBooleanType()) {
3048 CK = CK_IntegralToBoolean;
3049 } else if (type->isObjCObjectPointerType()) {
3050 if (SubExpr->getType()->isBlockPointerType()) {
3051 CK = CK_BlockPointerToObjCPointerCast;
3052 } else if (SubExpr->getType()->isPointerType()) {
3053 CK = CK_CPointerToObjCPointerCast;
3054 } else {
3055 CK = CK_BitCast;
3056 }
3057 } else {
3058 CK = CK_BitCast;
3059 }
3060
3061 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3062 }
3063 // Make id<P...> cast into an 'id' cast.
3064 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3065 if (CE->getType()->isObjCQualifiedIdType()) {
3066 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3067 userExpr = CE->getSubExpr();
3068 CastKind CK;
3069 if (userExpr->getType()->isIntegralType(*Context)) {
3070 CK = CK_IntegralToPointer;
3071 } else if (userExpr->getType()->isBlockPointerType()) {
3072 CK = CK_BlockPointerToObjCPointerCast;
3073 } else if (userExpr->getType()->isPointerType()) {
3074 CK = CK_CPointerToObjCPointerCast;
3075 } else {
3076 CK = CK_BitCast;
3077 }
3078 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3079 CK, userExpr);
3080 }
3081 }
3082 MsgExprs.push_back(userExpr);
3083 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3084 // out the argument in the original expression (since we aren't deleting
3085 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3086 //Exp->setArg(i, 0);
3087 }
3088 // Generate the funky cast.
3089 CastExpr *cast;
3090 SmallVector<QualType, 8> ArgTypes;
3091 QualType returnType;
3092
3093 // Push 'id' and 'SEL', the 2 implicit arguments.
3094 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3095 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3096 else
3097 ArgTypes.push_back(Context->getObjCIdType());
3098 ArgTypes.push_back(Context->getObjCSelType());
3099 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3100 // Push any user argument types.
3101 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3102 E = OMD->param_end(); PI != E; ++PI) {
3103 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3104 ? Context->getObjCIdType()
3105 : (*PI)->getType();
3106 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3107 (void)convertBlockPointerToFunctionPointer(t);
3108 ArgTypes.push_back(t);
3109 }
3110 returnType = Exp->getType();
3111 convertToUnqualifiedObjCType(returnType);
3112 (void)convertBlockPointerToFunctionPointer(returnType);
3113 } else {
3114 returnType = Context->getObjCIdType();
3115 }
3116 // Get the type, we will need to reference it in a couple spots.
3117 QualType msgSendType = MsgSendFlavor->getType();
3118
3119 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003120 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003121 VK_LValue, SourceLocation());
3122
3123 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3124 // If we don't do this cast, we get the following bizarre warning/note:
3125 // xx.m:13: warning: function called through a non-compatible type
3126 // xx.m:13: note: if this code is reached, the program will abort
3127 cast = NoTypeInfoCStyleCastExpr(Context,
3128 Context->getPointerType(Context->VoidTy),
3129 CK_BitCast, DRE);
3130
3131 // Now do the "normal" pointer to function cast.
3132 QualType castType =
3133 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3134 // If we don't have a method decl, force a variadic cast.
3135 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3136 castType = Context->getPointerType(castType);
3137 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3138 cast);
3139
3140 // Don't forget the parens to enforce the proper binding.
3141 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3142
3143 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3144 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3145 MsgExprs.size(),
3146 FT->getResultType(), VK_RValue,
3147 EndLoc);
3148 Stmt *ReplacingStmt = CE;
3149 if (MsgSendStretFlavor) {
3150 // We have the method which returns a struct/union. Must also generate
3151 // call to objc_msgSend_stret and hang both varieties on a conditional
3152 // expression which dictate which one to envoke depending on size of
3153 // method's return type.
3154
3155 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003156 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3157 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003158 VK_LValue, SourceLocation());
3159 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3160 cast = NoTypeInfoCStyleCastExpr(Context,
3161 Context->getPointerType(Context->VoidTy),
3162 CK_BitCast, STDRE);
3163 // Now do the "normal" pointer to function cast.
3164 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3165 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3166 castType = Context->getPointerType(castType);
3167 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3168 cast);
3169
3170 // Don't forget the parens to enforce the proper binding.
3171 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3172
3173 FT = msgSendType->getAs<FunctionType>();
3174 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3175 MsgExprs.size(),
3176 FT->getResultType(), VK_RValue,
3177 SourceLocation());
3178
3179 // Build sizeof(returnType)
3180 UnaryExprOrTypeTraitExpr *sizeofExpr =
3181 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3182 Context->getTrivialTypeSourceInfo(returnType),
3183 Context->getSizeType(), SourceLocation(),
3184 SourceLocation());
3185 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3186 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3187 // For X86 it is more complicated and some kind of target specific routine
3188 // is needed to decide what to do.
3189 unsigned IntSize =
3190 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3191 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3192 llvm::APInt(IntSize, 8),
3193 Context->IntTy,
3194 SourceLocation());
3195 BinaryOperator *lessThanExpr =
3196 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3197 VK_RValue, OK_Ordinary, SourceLocation());
3198 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3199 ConditionalOperator *CondExpr =
3200 new (Context) ConditionalOperator(lessThanExpr,
3201 SourceLocation(), CE,
3202 SourceLocation(), STCE,
3203 returnType, VK_RValue, OK_Ordinary);
3204 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3205 CondExpr);
3206 }
3207 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3208 return ReplacingStmt;
3209}
3210
3211Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3212 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3213 Exp->getLocEnd());
3214
3215 // Now do the actual rewrite.
3216 ReplaceStmt(Exp, ReplacingStmt);
3217
3218 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3219 return ReplacingStmt;
3220}
3221
3222// typedef struct objc_object Protocol;
3223QualType RewriteModernObjC::getProtocolType() {
3224 if (!ProtocolTypeDecl) {
3225 TypeSourceInfo *TInfo
3226 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3227 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3228 SourceLocation(), SourceLocation(),
3229 &Context->Idents.get("Protocol"),
3230 TInfo);
3231 }
3232 return Context->getTypeDeclType(ProtocolTypeDecl);
3233}
3234
3235/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3236/// a synthesized/forward data reference (to the protocol's metadata).
3237/// The forward references (and metadata) are generated in
3238/// RewriteModernObjC::HandleTranslationUnit().
3239Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003240 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3241 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003242 IdentifierInfo *ID = &Context->Idents.get(Name);
3243 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3244 SourceLocation(), ID, getProtocolType(), 0,
3245 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003246 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3247 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003248 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3249 Context->getPointerType(DRE->getType()),
3250 VK_RValue, OK_Ordinary, SourceLocation());
3251 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3252 CK_BitCast,
3253 DerefExpr);
3254 ReplaceStmt(Exp, castExpr);
3255 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3256 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3257 return castExpr;
3258
3259}
3260
3261bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3262 const char *endBuf) {
3263 while (startBuf < endBuf) {
3264 if (*startBuf == '#') {
3265 // Skip whitespace.
3266 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3267 ;
3268 if (!strncmp(startBuf, "if", strlen("if")) ||
3269 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3270 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3271 !strncmp(startBuf, "define", strlen("define")) ||
3272 !strncmp(startBuf, "undef", strlen("undef")) ||
3273 !strncmp(startBuf, "else", strlen("else")) ||
3274 !strncmp(startBuf, "elif", strlen("elif")) ||
3275 !strncmp(startBuf, "endif", strlen("endif")) ||
3276 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3277 !strncmp(startBuf, "include", strlen("include")) ||
3278 !strncmp(startBuf, "import", strlen("import")) ||
3279 !strncmp(startBuf, "include_next", strlen("include_next")))
3280 return true;
3281 }
3282 startBuf++;
3283 }
3284 return false;
3285}
3286
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003287/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003288/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003289bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3290 std::string &Result) {
3291 if (Type->isArrayType()) {
3292 QualType ElemTy = Context->getBaseElementType(Type);
3293 return RewriteObjCFieldDeclType(ElemTy, Result);
3294 }
3295 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003296 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3297 if (RD->isCompleteDefinition()) {
3298 if (RD->isStruct())
3299 Result += "\n\tstruct ";
3300 else if (RD->isUnion())
3301 Result += "\n\tunion ";
3302 else
3303 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003304
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003305 Result += RD->getName();
3306 if (TagsDefinedInIvarDecls.count(RD)) {
3307 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003308 Result += " ";
3309 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003310 }
3311 TagsDefinedInIvarDecls.insert(RD);
3312 Result += " {\n";
3313 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003314 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003315 FieldDecl *FD = *i;
3316 RewriteObjCFieldDecl(FD, Result);
3317 }
3318 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003319 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003320 }
3321 }
3322 else if (Type->isEnumeralType()) {
3323 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3324 if (ED->isCompleteDefinition()) {
3325 Result += "\n\tenum ";
3326 Result += ED->getName();
3327 if (TagsDefinedInIvarDecls.count(ED)) {
3328 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003329 Result += " ";
3330 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003331 }
3332 TagsDefinedInIvarDecls.insert(ED);
3333
3334 Result += " {\n";
3335 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3336 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3337 Result += "\t"; Result += EC->getName(); Result += " = ";
3338 llvm::APSInt Val = EC->getInitVal();
3339 Result += Val.toString(10);
3340 Result += ",\n";
3341 }
3342 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003343 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003344 }
3345 }
3346
3347 Result += "\t";
3348 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003349 return false;
3350}
3351
3352
3353/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3354/// It handles elaborated types, as well as enum types in the process.
3355void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3356 std::string &Result) {
3357 QualType Type = fieldDecl->getType();
3358 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003359
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003360 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3361 if (!EleboratedType)
3362 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003363 Result += Name;
3364 if (fieldDecl->isBitField()) {
3365 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3366 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003367 else if (EleboratedType && Type->isArrayType()) {
3368 CanQualType CType = Context->getCanonicalType(Type);
3369 while (isa<ArrayType>(CType)) {
3370 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3371 Result += "[";
3372 llvm::APInt Dim = CAT->getSize();
3373 Result += utostr(Dim.getZExtValue());
3374 Result += "]";
3375 }
3376 CType = CType->getAs<ArrayType>()->getElementType();
3377 }
3378 }
3379
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003380 Result += ";\n";
3381}
3382
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003383/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3384/// an objective-c class with ivars.
3385void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3386 std::string &Result) {
3387 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3388 assert(CDecl->getName() != "" &&
3389 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003390 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003391 SmallVector<ObjCIvarDecl *, 8> IVars;
3392 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003393 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003394 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003395
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003396 SourceLocation LocStart = CDecl->getLocStart();
3397 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003398
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003399 const char *startBuf = SM->getCharacterData(LocStart);
3400 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003401
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003402 // If no ivars and no root or if its root, directly or indirectly,
3403 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003404 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003405 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3406 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3407 ReplaceText(LocStart, endBuf-startBuf, Result);
3408 return;
3409 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003410
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003411 Result += "\nstruct ";
3412 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003413 Result += "_IMPL {\n";
3414
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003415 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003416 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3417 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3418 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003419 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003420 TagsDefinedInIvarDecls.clear();
3421 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3422 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003423
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003424 Result += "};\n";
3425 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3426 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003427 // Mark this struct as having been generated.
3428 if (!ObjCSynthesizedStructs.insert(CDecl))
3429 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003430}
3431
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003432static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3433 ObjCIvarDecl *IvarDecl, std::string &Result) {
3434 Result += "OBJC_IVAR_$_";
3435 Result += IDecl->getName();
3436 Result += "$";
3437 Result += IvarDecl->getName();
3438}
3439
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003440/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3441/// have been referenced in an ivar access expression.
3442void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3443 std::string &Result) {
3444 // write out ivar offset symbols which have been referenced in an ivar
3445 // access expression.
3446 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3447 if (Ivars.empty())
3448 return;
3449 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3450 e = Ivars.end(); i != e; i++) {
3451 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003452 Result += "\n";
3453 if (LangOpts.MicrosoftExt)
3454 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003455 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003456 if (LangOpts.MicrosoftExt &&
3457 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003458 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3459 Result += "__declspec(dllimport) ";
3460
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003461 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003462 WriteInternalIvarName(CDecl, IvarDecl, Result);
3463 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003464 }
3465}
3466
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003467//===----------------------------------------------------------------------===//
3468// Meta Data Emission
3469//===----------------------------------------------------------------------===//
3470
3471
3472/// RewriteImplementations - This routine rewrites all method implementations
3473/// and emits meta-data.
3474
3475void RewriteModernObjC::RewriteImplementations() {
3476 int ClsDefCount = ClassImplementation.size();
3477 int CatDefCount = CategoryImplementation.size();
3478
3479 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003480 for (int i = 0; i < ClsDefCount; i++) {
3481 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3482 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3483 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003484 assert(false &&
3485 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003486 RewriteImplementationDecl(OIMP);
3487 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003488
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003489 for (int i = 0; i < CatDefCount; i++) {
3490 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3491 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3492 if (CDecl->isImplicitInterfaceDecl())
3493 assert(false &&
3494 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003495 RewriteImplementationDecl(CIMP);
3496 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003497}
3498
3499void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3500 const std::string &Name,
3501 ValueDecl *VD, bool def) {
3502 assert(BlockByRefDeclNo.count(VD) &&
3503 "RewriteByRefString: ByRef decl missing");
3504 if (def)
3505 ResultStr += "struct ";
3506 ResultStr += "__Block_byref_" + Name +
3507 "_" + utostr(BlockByRefDeclNo[VD]) ;
3508}
3509
3510static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3511 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3512 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3513 return false;
3514}
3515
3516std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3517 StringRef funcName,
3518 std::string Tag) {
3519 const FunctionType *AFT = CE->getFunctionType();
3520 QualType RT = AFT->getResultType();
3521 std::string StructRef = "struct " + Tag;
3522 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003523 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003524
3525 BlockDecl *BD = CE->getBlockDecl();
3526
3527 if (isa<FunctionNoProtoType>(AFT)) {
3528 // No user-supplied arguments. Still need to pass in a pointer to the
3529 // block (to reference imported block decl refs).
3530 S += "(" + StructRef + " *__cself)";
3531 } else if (BD->param_empty()) {
3532 S += "(" + StructRef + " *__cself)";
3533 } else {
3534 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3535 assert(FT && "SynthesizeBlockFunc: No function proto");
3536 S += '(';
3537 // first add the implicit argument.
3538 S += StructRef + " *__cself, ";
3539 std::string ParamStr;
3540 for (BlockDecl::param_iterator AI = BD->param_begin(),
3541 E = BD->param_end(); AI != E; ++AI) {
3542 if (AI != BD->param_begin()) S += ", ";
3543 ParamStr = (*AI)->getNameAsString();
3544 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003545 (void)convertBlockPointerToFunctionPointer(QT);
3546 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003547 S += ParamStr;
3548 }
3549 if (FT->isVariadic()) {
3550 if (!BD->param_empty()) S += ", ";
3551 S += "...";
3552 }
3553 S += ')';
3554 }
3555 S += " {\n";
3556
3557 // Create local declarations to avoid rewriting all closure decl ref exprs.
3558 // First, emit a declaration for all "by ref" decls.
3559 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3560 E = BlockByRefDecls.end(); I != E; ++I) {
3561 S += " ";
3562 std::string Name = (*I)->getNameAsString();
3563 std::string TypeString;
3564 RewriteByRefString(TypeString, Name, (*I));
3565 TypeString += " *";
3566 Name = TypeString + Name;
3567 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3568 }
3569 // Next, emit a declaration for all "by copy" declarations.
3570 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3571 E = BlockByCopyDecls.end(); I != E; ++I) {
3572 S += " ";
3573 // Handle nested closure invocation. For example:
3574 //
3575 // void (^myImportedClosure)(void);
3576 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3577 //
3578 // void (^anotherClosure)(void);
3579 // anotherClosure = ^(void) {
3580 // myImportedClosure(); // import and invoke the closure
3581 // };
3582 //
3583 if (isTopLevelBlockPointerType((*I)->getType())) {
3584 RewriteBlockPointerTypeVariable(S, (*I));
3585 S += " = (";
3586 RewriteBlockPointerType(S, (*I)->getType());
3587 S += ")";
3588 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3589 }
3590 else {
3591 std::string Name = (*I)->getNameAsString();
3592 QualType QT = (*I)->getType();
3593 if (HasLocalVariableExternalStorage(*I))
3594 QT = Context->getPointerType(QT);
3595 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3596 S += Name + " = __cself->" +
3597 (*I)->getNameAsString() + "; // bound by copy\n";
3598 }
3599 }
3600 std::string RewrittenStr = RewrittenBlockExprs[CE];
3601 const char *cstr = RewrittenStr.c_str();
3602 while (*cstr++ != '{') ;
3603 S += cstr;
3604 S += "\n";
3605 return S;
3606}
3607
3608std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3609 StringRef funcName,
3610 std::string Tag) {
3611 std::string StructRef = "struct " + Tag;
3612 std::string S = "static void __";
3613
3614 S += funcName;
3615 S += "_block_copy_" + utostr(i);
3616 S += "(" + StructRef;
3617 S += "*dst, " + StructRef;
3618 S += "*src) {";
3619 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3620 E = ImportedBlockDecls.end(); I != E; ++I) {
3621 ValueDecl *VD = (*I);
3622 S += "_Block_object_assign((void*)&dst->";
3623 S += (*I)->getNameAsString();
3624 S += ", (void*)src->";
3625 S += (*I)->getNameAsString();
3626 if (BlockByRefDeclsPtrSet.count((*I)))
3627 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3628 else if (VD->getType()->isBlockPointerType())
3629 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3630 else
3631 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3632 }
3633 S += "}\n";
3634
3635 S += "\nstatic void __";
3636 S += funcName;
3637 S += "_block_dispose_" + utostr(i);
3638 S += "(" + StructRef;
3639 S += "*src) {";
3640 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3641 E = ImportedBlockDecls.end(); I != E; ++I) {
3642 ValueDecl *VD = (*I);
3643 S += "_Block_object_dispose((void*)src->";
3644 S += (*I)->getNameAsString();
3645 if (BlockByRefDeclsPtrSet.count((*I)))
3646 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3647 else if (VD->getType()->isBlockPointerType())
3648 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3649 else
3650 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3651 }
3652 S += "}\n";
3653 return S;
3654}
3655
3656std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3657 std::string Desc) {
3658 std::string S = "\nstruct " + Tag;
3659 std::string Constructor = " " + Tag;
3660
3661 S += " {\n struct __block_impl impl;\n";
3662 S += " struct " + Desc;
3663 S += "* Desc;\n";
3664
3665 Constructor += "(void *fp, "; // Invoke function pointer.
3666 Constructor += "struct " + Desc; // Descriptor pointer.
3667 Constructor += " *desc";
3668
3669 if (BlockDeclRefs.size()) {
3670 // Output all "by copy" declarations.
3671 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3672 E = BlockByCopyDecls.end(); I != E; ++I) {
3673 S += " ";
3674 std::string FieldName = (*I)->getNameAsString();
3675 std::string ArgName = "_" + FieldName;
3676 // Handle nested closure invocation. For example:
3677 //
3678 // void (^myImportedBlock)(void);
3679 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3680 //
3681 // void (^anotherBlock)(void);
3682 // anotherBlock = ^(void) {
3683 // myImportedBlock(); // import and invoke the closure
3684 // };
3685 //
3686 if (isTopLevelBlockPointerType((*I)->getType())) {
3687 S += "struct __block_impl *";
3688 Constructor += ", void *" + ArgName;
3689 } else {
3690 QualType QT = (*I)->getType();
3691 if (HasLocalVariableExternalStorage(*I))
3692 QT = Context->getPointerType(QT);
3693 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3694 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3695 Constructor += ", " + ArgName;
3696 }
3697 S += FieldName + ";\n";
3698 }
3699 // Output all "by ref" declarations.
3700 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3701 E = BlockByRefDecls.end(); I != E; ++I) {
3702 S += " ";
3703 std::string FieldName = (*I)->getNameAsString();
3704 std::string ArgName = "_" + FieldName;
3705 {
3706 std::string TypeString;
3707 RewriteByRefString(TypeString, FieldName, (*I));
3708 TypeString += " *";
3709 FieldName = TypeString + FieldName;
3710 ArgName = TypeString + ArgName;
3711 Constructor += ", " + ArgName;
3712 }
3713 S += FieldName + "; // by ref\n";
3714 }
3715 // Finish writing the constructor.
3716 Constructor += ", int flags=0)";
3717 // Initialize all "by copy" arguments.
3718 bool firsTime = true;
3719 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3720 E = BlockByCopyDecls.end(); I != E; ++I) {
3721 std::string Name = (*I)->getNameAsString();
3722 if (firsTime) {
3723 Constructor += " : ";
3724 firsTime = false;
3725 }
3726 else
3727 Constructor += ", ";
3728 if (isTopLevelBlockPointerType((*I)->getType()))
3729 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3730 else
3731 Constructor += Name + "(_" + Name + ")";
3732 }
3733 // Initialize all "by ref" arguments.
3734 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3735 E = BlockByRefDecls.end(); I != E; ++I) {
3736 std::string Name = (*I)->getNameAsString();
3737 if (firsTime) {
3738 Constructor += " : ";
3739 firsTime = false;
3740 }
3741 else
3742 Constructor += ", ";
3743 Constructor += Name + "(_" + Name + "->__forwarding)";
3744 }
3745
3746 Constructor += " {\n";
3747 if (GlobalVarDecl)
3748 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3749 else
3750 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3751 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3752
3753 Constructor += " Desc = desc;\n";
3754 } else {
3755 // Finish writing the constructor.
3756 Constructor += ", int flags=0) {\n";
3757 if (GlobalVarDecl)
3758 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3759 else
3760 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3761 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3762 Constructor += " Desc = desc;\n";
3763 }
3764 Constructor += " ";
3765 Constructor += "}\n";
3766 S += Constructor;
3767 S += "};\n";
3768 return S;
3769}
3770
3771std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3772 std::string ImplTag, int i,
3773 StringRef FunName,
3774 unsigned hasCopy) {
3775 std::string S = "\nstatic struct " + DescTag;
3776
3777 S += " {\n unsigned long reserved;\n";
3778 S += " unsigned long Block_size;\n";
3779 if (hasCopy) {
3780 S += " void (*copy)(struct ";
3781 S += ImplTag; S += "*, struct ";
3782 S += ImplTag; S += "*);\n";
3783
3784 S += " void (*dispose)(struct ";
3785 S += ImplTag; S += "*);\n";
3786 }
3787 S += "} ";
3788
3789 S += DescTag + "_DATA = { 0, sizeof(struct ";
3790 S += ImplTag + ")";
3791 if (hasCopy) {
3792 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3793 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3794 }
3795 S += "};\n";
3796 return S;
3797}
3798
3799void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3800 StringRef FunName) {
3801 // Insert declaration for the function in which block literal is used.
3802 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3803 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3804 bool RewriteSC = (GlobalVarDecl &&
3805 !Blocks.empty() &&
3806 GlobalVarDecl->getStorageClass() == SC_Static &&
3807 GlobalVarDecl->getType().getCVRQualifiers());
3808 if (RewriteSC) {
3809 std::string SC(" void __");
3810 SC += GlobalVarDecl->getNameAsString();
3811 SC += "() {}";
3812 InsertText(FunLocStart, SC);
3813 }
3814
3815 // Insert closures that were part of the function.
3816 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3817 CollectBlockDeclRefInfo(Blocks[i]);
3818 // Need to copy-in the inner copied-in variables not actually used in this
3819 // block.
3820 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003821 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003822 ValueDecl *VD = Exp->getDecl();
3823 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003824 if (!VD->hasAttr<BlocksAttr>()) {
3825 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3826 BlockByCopyDeclsPtrSet.insert(VD);
3827 BlockByCopyDecls.push_back(VD);
3828 }
3829 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003830 }
John McCallf4b88a42012-03-10 09:33:50 +00003831
3832 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003833 BlockByRefDeclsPtrSet.insert(VD);
3834 BlockByRefDecls.push_back(VD);
3835 }
John McCallf4b88a42012-03-10 09:33:50 +00003836
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003837 // imported objects in the inner blocks not used in the outer
3838 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003839 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003840 VD->getType()->isBlockPointerType())
3841 ImportedBlockDecls.insert(VD);
3842 }
3843
3844 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3845 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3846
3847 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3848
3849 InsertText(FunLocStart, CI);
3850
3851 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3852
3853 InsertText(FunLocStart, CF);
3854
3855 if (ImportedBlockDecls.size()) {
3856 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3857 InsertText(FunLocStart, HF);
3858 }
3859 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3860 ImportedBlockDecls.size() > 0);
3861 InsertText(FunLocStart, BD);
3862
3863 BlockDeclRefs.clear();
3864 BlockByRefDecls.clear();
3865 BlockByRefDeclsPtrSet.clear();
3866 BlockByCopyDecls.clear();
3867 BlockByCopyDeclsPtrSet.clear();
3868 ImportedBlockDecls.clear();
3869 }
3870 if (RewriteSC) {
3871 // Must insert any 'const/volatile/static here. Since it has been
3872 // removed as result of rewriting of block literals.
3873 std::string SC;
3874 if (GlobalVarDecl->getStorageClass() == SC_Static)
3875 SC = "static ";
3876 if (GlobalVarDecl->getType().isConstQualified())
3877 SC += "const ";
3878 if (GlobalVarDecl->getType().isVolatileQualified())
3879 SC += "volatile ";
3880 if (GlobalVarDecl->getType().isRestrictQualified())
3881 SC += "restrict ";
3882 InsertText(FunLocStart, SC);
3883 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003884 if (GlobalConstructionExp) {
3885 // extra fancy dance for global literal expression.
3886
3887 // Always the latest block expression on the block stack.
3888 std::string Tag = "__";
3889 Tag += FunName;
3890 Tag += "_block_impl_";
3891 Tag += utostr(Blocks.size()-1);
3892 std::string globalBuf = "static ";
3893 globalBuf += Tag; globalBuf += " ";
3894 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003895
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003896 llvm::raw_string_ostream constructorExprBuf(SStr);
3897 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
3898 PrintingPolicy(LangOpts));
3899 globalBuf += constructorExprBuf.str();
3900 globalBuf += ";\n";
3901 InsertText(FunLocStart, globalBuf);
3902 GlobalConstructionExp = 0;
3903 }
3904
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003905 Blocks.clear();
3906 InnerDeclRefsCount.clear();
3907 InnerDeclRefs.clear();
3908 RewrittenBlockExprs.clear();
3909}
3910
3911void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3912 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3913 StringRef FuncName = FD->getName();
3914
3915 SynthesizeBlockLiterals(FunLocStart, FuncName);
3916}
3917
3918static void BuildUniqueMethodName(std::string &Name,
3919 ObjCMethodDecl *MD) {
3920 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3921 Name = IFace->getName();
3922 Name += "__" + MD->getSelector().getAsString();
3923 // Convert colons to underscores.
3924 std::string::size_type loc = 0;
3925 while ((loc = Name.find(":", loc)) != std::string::npos)
3926 Name.replace(loc, 1, "_");
3927}
3928
3929void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3930 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3931 //SourceLocation FunLocStart = MD->getLocStart();
3932 SourceLocation FunLocStart = MD->getLocStart();
3933 std::string FuncName;
3934 BuildUniqueMethodName(FuncName, MD);
3935 SynthesizeBlockLiterals(FunLocStart, FuncName);
3936}
3937
3938void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3939 for (Stmt::child_range CI = S->children(); CI; ++CI)
3940 if (*CI) {
3941 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3942 GetBlockDeclRefExprs(CBE->getBody());
3943 else
3944 GetBlockDeclRefExprs(*CI);
3945 }
3946 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003947 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3948 if (DRE->refersToEnclosingLocal() &&
3949 HasLocalVariableExternalStorage(DRE->getDecl())) {
3950 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003951 }
3952
3953 return;
3954}
3955
3956void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003957 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003958 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3959 for (Stmt::child_range CI = S->children(); CI; ++CI)
3960 if (*CI) {
3961 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3962 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3963 GetInnerBlockDeclRefExprs(CBE->getBody(),
3964 InnerBlockDeclRefs,
3965 InnerContexts);
3966 }
3967 else
3968 GetInnerBlockDeclRefExprs(*CI,
3969 InnerBlockDeclRefs,
3970 InnerContexts);
3971
3972 }
3973 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003974 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3975 if (DRE->refersToEnclosingLocal()) {
3976 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3977 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3978 InnerBlockDeclRefs.push_back(DRE);
3979 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3980 if (Var->isFunctionOrMethodVarDecl())
3981 ImportedLocalExternalDecls.insert(Var);
3982 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003983 }
3984
3985 return;
3986}
3987
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003988/// convertObjCTypeToCStyleType - This routine converts such objc types
3989/// as qualified objects, and blocks to their closest c/c++ types that
3990/// it can. It returns true if input type was modified.
3991bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3992 QualType oldT = T;
3993 convertBlockPointerToFunctionPointer(T);
3994 if (T->isFunctionPointerType()) {
3995 QualType PointeeTy;
3996 if (const PointerType* PT = T->getAs<PointerType>()) {
3997 PointeeTy = PT->getPointeeType();
3998 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3999 T = convertFunctionTypeOfBlocks(FT);
4000 T = Context->getPointerType(T);
4001 }
4002 }
4003 }
4004
4005 convertToUnqualifiedObjCType(T);
4006 return T != oldT;
4007}
4008
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004009/// convertFunctionTypeOfBlocks - This routine converts a function type
4010/// whose result type may be a block pointer or whose argument type(s)
4011/// might be block pointers to an equivalent function type replacing
4012/// all block pointers to function pointers.
4013QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4014 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4015 // FTP will be null for closures that don't take arguments.
4016 // Generate a funky cast.
4017 SmallVector<QualType, 8> ArgTypes;
4018 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004019 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004020
4021 if (FTP) {
4022 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4023 E = FTP->arg_type_end(); I && (I != E); ++I) {
4024 QualType t = *I;
4025 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004026 if (convertObjCTypeToCStyleType(t))
4027 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004028 ArgTypes.push_back(t);
4029 }
4030 }
4031 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004032 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004033 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4034 else FuncType = QualType(FT, 0);
4035 return FuncType;
4036}
4037
4038Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4039 // Navigate to relevant type information.
4040 const BlockPointerType *CPT = 0;
4041
4042 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4043 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004044 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4045 CPT = MExpr->getType()->getAs<BlockPointerType>();
4046 }
4047 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4048 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4049 }
4050 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4051 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4052 else if (const ConditionalOperator *CEXPR =
4053 dyn_cast<ConditionalOperator>(BlockExp)) {
4054 Expr *LHSExp = CEXPR->getLHS();
4055 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4056 Expr *RHSExp = CEXPR->getRHS();
4057 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4058 Expr *CONDExp = CEXPR->getCond();
4059 ConditionalOperator *CondExpr =
4060 new (Context) ConditionalOperator(CONDExp,
4061 SourceLocation(), cast<Expr>(LHSStmt),
4062 SourceLocation(), cast<Expr>(RHSStmt),
4063 Exp->getType(), VK_RValue, OK_Ordinary);
4064 return CondExpr;
4065 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4066 CPT = IRE->getType()->getAs<BlockPointerType>();
4067 } else if (const PseudoObjectExpr *POE
4068 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4069 CPT = POE->getType()->castAs<BlockPointerType>();
4070 } else {
4071 assert(1 && "RewriteBlockClass: Bad type");
4072 }
4073 assert(CPT && "RewriteBlockClass: Bad type");
4074 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4075 assert(FT && "RewriteBlockClass: Bad type");
4076 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4077 // FTP will be null for closures that don't take arguments.
4078
4079 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4080 SourceLocation(), SourceLocation(),
4081 &Context->Idents.get("__block_impl"));
4082 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4083
4084 // Generate a funky cast.
4085 SmallVector<QualType, 8> ArgTypes;
4086
4087 // Push the block argument type.
4088 ArgTypes.push_back(PtrBlock);
4089 if (FTP) {
4090 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4091 E = FTP->arg_type_end(); I && (I != E); ++I) {
4092 QualType t = *I;
4093 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4094 if (!convertBlockPointerToFunctionPointer(t))
4095 convertToUnqualifiedObjCType(t);
4096 ArgTypes.push_back(t);
4097 }
4098 }
4099 // Now do the pointer to function cast.
4100 QualType PtrToFuncCastType
4101 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4102
4103 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4104
4105 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4106 CK_BitCast,
4107 const_cast<Expr*>(BlockExp));
4108 // Don't forget the parens to enforce the proper binding.
4109 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4110 BlkCast);
4111 //PE->dump();
4112
4113 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4114 SourceLocation(),
4115 &Context->Idents.get("FuncPtr"),
4116 Context->VoidPtrTy, 0,
4117 /*BitWidth=*/0, /*Mutable=*/true,
4118 /*HasInit=*/false);
4119 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4120 FD->getType(), VK_LValue,
4121 OK_Ordinary);
4122
4123
4124 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4125 CK_BitCast, ME);
4126 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4127
4128 SmallVector<Expr*, 8> BlkExprs;
4129 // Add the implicit argument.
4130 BlkExprs.push_back(BlkCast);
4131 // Add the user arguments.
4132 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4133 E = Exp->arg_end(); I != E; ++I) {
4134 BlkExprs.push_back(*I);
4135 }
4136 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4137 BlkExprs.size(),
4138 Exp->getType(), VK_RValue,
4139 SourceLocation());
4140 return CE;
4141}
4142
4143// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004144// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004145// For example:
4146//
4147// int main() {
4148// __block Foo *f;
4149// __block int i;
4150//
4151// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004152// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004153// i = 77;
4154// };
4155//}
John McCallf4b88a42012-03-10 09:33:50 +00004156Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004157 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4158 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004159 ValueDecl *VD = DeclRefExp->getDecl();
4160 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004161
4162 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4163 SourceLocation(),
4164 &Context->Idents.get("__forwarding"),
4165 Context->VoidPtrTy, 0,
4166 /*BitWidth=*/0, /*Mutable=*/true,
4167 /*HasInit=*/false);
4168 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4169 FD, SourceLocation(),
4170 FD->getType(), VK_LValue,
4171 OK_Ordinary);
4172
4173 StringRef Name = VD->getName();
4174 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4175 &Context->Idents.get(Name),
4176 Context->VoidPtrTy, 0,
4177 /*BitWidth=*/0, /*Mutable=*/true,
4178 /*HasInit=*/false);
4179 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4180 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4181
4182
4183
4184 // Need parens to enforce precedence.
4185 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4186 DeclRefExp->getExprLoc(),
4187 ME);
4188 ReplaceStmt(DeclRefExp, PE);
4189 return PE;
4190}
4191
4192// Rewrites the imported local variable V with external storage
4193// (static, extern, etc.) as *V
4194//
4195Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4196 ValueDecl *VD = DRE->getDecl();
4197 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4198 if (!ImportedLocalExternalDecls.count(Var))
4199 return DRE;
4200 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4201 VK_LValue, OK_Ordinary,
4202 DRE->getLocation());
4203 // Need parens to enforce precedence.
4204 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4205 Exp);
4206 ReplaceStmt(DRE, PE);
4207 return PE;
4208}
4209
4210void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4211 SourceLocation LocStart = CE->getLParenLoc();
4212 SourceLocation LocEnd = CE->getRParenLoc();
4213
4214 // Need to avoid trying to rewrite synthesized casts.
4215 if (LocStart.isInvalid())
4216 return;
4217 // Need to avoid trying to rewrite casts contained in macros.
4218 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4219 return;
4220
4221 const char *startBuf = SM->getCharacterData(LocStart);
4222 const char *endBuf = SM->getCharacterData(LocEnd);
4223 QualType QT = CE->getType();
4224 const Type* TypePtr = QT->getAs<Type>();
4225 if (isa<TypeOfExprType>(TypePtr)) {
4226 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4227 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4228 std::string TypeAsString = "(";
4229 RewriteBlockPointerType(TypeAsString, QT);
4230 TypeAsString += ")";
4231 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4232 return;
4233 }
4234 // advance the location to startArgList.
4235 const char *argPtr = startBuf;
4236
4237 while (*argPtr++ && (argPtr < endBuf)) {
4238 switch (*argPtr) {
4239 case '^':
4240 // Replace the '^' with '*'.
4241 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4242 ReplaceText(LocStart, 1, "*");
4243 break;
4244 }
4245 }
4246 return;
4247}
4248
4249void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4250 SourceLocation DeclLoc = FD->getLocation();
4251 unsigned parenCount = 0;
4252
4253 // We have 1 or more arguments that have closure pointers.
4254 const char *startBuf = SM->getCharacterData(DeclLoc);
4255 const char *startArgList = strchr(startBuf, '(');
4256
4257 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4258
4259 parenCount++;
4260 // advance the location to startArgList.
4261 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4262 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4263
4264 const char *argPtr = startArgList;
4265
4266 while (*argPtr++ && parenCount) {
4267 switch (*argPtr) {
4268 case '^':
4269 // Replace the '^' with '*'.
4270 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4271 ReplaceText(DeclLoc, 1, "*");
4272 break;
4273 case '(':
4274 parenCount++;
4275 break;
4276 case ')':
4277 parenCount--;
4278 break;
4279 }
4280 }
4281 return;
4282}
4283
4284bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4285 const FunctionProtoType *FTP;
4286 const PointerType *PT = QT->getAs<PointerType>();
4287 if (PT) {
4288 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4289 } else {
4290 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4291 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4292 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4293 }
4294 if (FTP) {
4295 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4296 E = FTP->arg_type_end(); I != E; ++I)
4297 if (isTopLevelBlockPointerType(*I))
4298 return true;
4299 }
4300 return false;
4301}
4302
4303bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4304 const FunctionProtoType *FTP;
4305 const PointerType *PT = QT->getAs<PointerType>();
4306 if (PT) {
4307 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4308 } else {
4309 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4310 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4311 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4312 }
4313 if (FTP) {
4314 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4315 E = FTP->arg_type_end(); I != E; ++I) {
4316 if ((*I)->isObjCQualifiedIdType())
4317 return true;
4318 if ((*I)->isObjCObjectPointerType() &&
4319 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4320 return true;
4321 }
4322
4323 }
4324 return false;
4325}
4326
4327void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4328 const char *&RParen) {
4329 const char *argPtr = strchr(Name, '(');
4330 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4331
4332 LParen = argPtr; // output the start.
4333 argPtr++; // skip past the left paren.
4334 unsigned parenCount = 1;
4335
4336 while (*argPtr && parenCount) {
4337 switch (*argPtr) {
4338 case '(': parenCount++; break;
4339 case ')': parenCount--; break;
4340 default: break;
4341 }
4342 if (parenCount) argPtr++;
4343 }
4344 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4345 RParen = argPtr; // output the end
4346}
4347
4348void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4349 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4350 RewriteBlockPointerFunctionArgs(FD);
4351 return;
4352 }
4353 // Handle Variables and Typedefs.
4354 SourceLocation DeclLoc = ND->getLocation();
4355 QualType DeclT;
4356 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4357 DeclT = VD->getType();
4358 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4359 DeclT = TDD->getUnderlyingType();
4360 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4361 DeclT = FD->getType();
4362 else
4363 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4364
4365 const char *startBuf = SM->getCharacterData(DeclLoc);
4366 const char *endBuf = startBuf;
4367 // scan backward (from the decl location) for the end of the previous decl.
4368 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4369 startBuf--;
4370 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4371 std::string buf;
4372 unsigned OrigLength=0;
4373 // *startBuf != '^' if we are dealing with a pointer to function that
4374 // may take block argument types (which will be handled below).
4375 if (*startBuf == '^') {
4376 // Replace the '^' with '*', computing a negative offset.
4377 buf = '*';
4378 startBuf++;
4379 OrigLength++;
4380 }
4381 while (*startBuf != ')') {
4382 buf += *startBuf;
4383 startBuf++;
4384 OrigLength++;
4385 }
4386 buf += ')';
4387 OrigLength++;
4388
4389 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4390 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4391 // Replace the '^' with '*' for arguments.
4392 // Replace id<P> with id/*<>*/
4393 DeclLoc = ND->getLocation();
4394 startBuf = SM->getCharacterData(DeclLoc);
4395 const char *argListBegin, *argListEnd;
4396 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4397 while (argListBegin < argListEnd) {
4398 if (*argListBegin == '^')
4399 buf += '*';
4400 else if (*argListBegin == '<') {
4401 buf += "/*";
4402 buf += *argListBegin++;
4403 OrigLength++;;
4404 while (*argListBegin != '>') {
4405 buf += *argListBegin++;
4406 OrigLength++;
4407 }
4408 buf += *argListBegin;
4409 buf += "*/";
4410 }
4411 else
4412 buf += *argListBegin;
4413 argListBegin++;
4414 OrigLength++;
4415 }
4416 buf += ')';
4417 OrigLength++;
4418 }
4419 ReplaceText(Start, OrigLength, buf);
4420
4421 return;
4422}
4423
4424
4425/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4426/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4427/// struct Block_byref_id_object *src) {
4428/// _Block_object_assign (&_dest->object, _src->object,
4429/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4430/// [|BLOCK_FIELD_IS_WEAK]) // object
4431/// _Block_object_assign(&_dest->object, _src->object,
4432/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4433/// [|BLOCK_FIELD_IS_WEAK]) // block
4434/// }
4435/// And:
4436/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4437/// _Block_object_dispose(_src->object,
4438/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4439/// [|BLOCK_FIELD_IS_WEAK]) // object
4440/// _Block_object_dispose(_src->object,
4441/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4442/// [|BLOCK_FIELD_IS_WEAK]) // block
4443/// }
4444
4445std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4446 int flag) {
4447 std::string S;
4448 if (CopyDestroyCache.count(flag))
4449 return S;
4450 CopyDestroyCache.insert(flag);
4451 S = "static void __Block_byref_id_object_copy_";
4452 S += utostr(flag);
4453 S += "(void *dst, void *src) {\n";
4454
4455 // offset into the object pointer is computed as:
4456 // void * + void* + int + int + void* + void *
4457 unsigned IntSize =
4458 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4459 unsigned VoidPtrSize =
4460 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4461
4462 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4463 S += " _Block_object_assign((char*)dst + ";
4464 S += utostr(offset);
4465 S += ", *(void * *) ((char*)src + ";
4466 S += utostr(offset);
4467 S += "), ";
4468 S += utostr(flag);
4469 S += ");\n}\n";
4470
4471 S += "static void __Block_byref_id_object_dispose_";
4472 S += utostr(flag);
4473 S += "(void *src) {\n";
4474 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4475 S += utostr(offset);
4476 S += "), ";
4477 S += utostr(flag);
4478 S += ");\n}\n";
4479 return S;
4480}
4481
4482/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4483/// the declaration into:
4484/// struct __Block_byref_ND {
4485/// void *__isa; // NULL for everything except __weak pointers
4486/// struct __Block_byref_ND *__forwarding;
4487/// int32_t __flags;
4488/// int32_t __size;
4489/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4490/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4491/// typex ND;
4492/// };
4493///
4494/// It then replaces declaration of ND variable with:
4495/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4496/// __size=sizeof(struct __Block_byref_ND),
4497/// ND=initializer-if-any};
4498///
4499///
4500void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4501 // Insert declaration for the function in which block literal is
4502 // used.
4503 if (CurFunctionDeclToDeclareForBlock)
4504 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4505 int flag = 0;
4506 int isa = 0;
4507 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4508 if (DeclLoc.isInvalid())
4509 // If type location is missing, it is because of missing type (a warning).
4510 // Use variable's location which is good for this case.
4511 DeclLoc = ND->getLocation();
4512 const char *startBuf = SM->getCharacterData(DeclLoc);
4513 SourceLocation X = ND->getLocEnd();
4514 X = SM->getExpansionLoc(X);
4515 const char *endBuf = SM->getCharacterData(X);
4516 std::string Name(ND->getNameAsString());
4517 std::string ByrefType;
4518 RewriteByRefString(ByrefType, Name, ND, true);
4519 ByrefType += " {\n";
4520 ByrefType += " void *__isa;\n";
4521 RewriteByRefString(ByrefType, Name, ND);
4522 ByrefType += " *__forwarding;\n";
4523 ByrefType += " int __flags;\n";
4524 ByrefType += " int __size;\n";
4525 // Add void *__Block_byref_id_object_copy;
4526 // void *__Block_byref_id_object_dispose; if needed.
4527 QualType Ty = ND->getType();
4528 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4529 if (HasCopyAndDispose) {
4530 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4531 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4532 }
4533
4534 QualType T = Ty;
4535 (void)convertBlockPointerToFunctionPointer(T);
4536 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4537
4538 ByrefType += " " + Name + ";\n";
4539 ByrefType += "};\n";
4540 // Insert this type in global scope. It is needed by helper function.
4541 SourceLocation FunLocStart;
4542 if (CurFunctionDef)
4543 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4544 else {
4545 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4546 FunLocStart = CurMethodDef->getLocStart();
4547 }
4548 InsertText(FunLocStart, ByrefType);
4549 if (Ty.isObjCGCWeak()) {
4550 flag |= BLOCK_FIELD_IS_WEAK;
4551 isa = 1;
4552 }
4553
4554 if (HasCopyAndDispose) {
4555 flag = BLOCK_BYREF_CALLER;
4556 QualType Ty = ND->getType();
4557 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4558 if (Ty->isBlockPointerType())
4559 flag |= BLOCK_FIELD_IS_BLOCK;
4560 else
4561 flag |= BLOCK_FIELD_IS_OBJECT;
4562 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4563 if (!HF.empty())
4564 InsertText(FunLocStart, HF);
4565 }
4566
4567 // struct __Block_byref_ND ND =
4568 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4569 // initializer-if-any};
4570 bool hasInit = (ND->getInit() != 0);
4571 unsigned flags = 0;
4572 if (HasCopyAndDispose)
4573 flags |= BLOCK_HAS_COPY_DISPOSE;
4574 Name = ND->getNameAsString();
4575 ByrefType.clear();
4576 RewriteByRefString(ByrefType, Name, ND);
4577 std::string ForwardingCastType("(");
4578 ForwardingCastType += ByrefType + " *)";
4579 if (!hasInit) {
4580 ByrefType += " " + Name + " = {(void*)";
4581 ByrefType += utostr(isa);
4582 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4583 ByrefType += utostr(flags);
4584 ByrefType += ", ";
4585 ByrefType += "sizeof(";
4586 RewriteByRefString(ByrefType, Name, ND);
4587 ByrefType += ")";
4588 if (HasCopyAndDispose) {
4589 ByrefType += ", __Block_byref_id_object_copy_";
4590 ByrefType += utostr(flag);
4591 ByrefType += ", __Block_byref_id_object_dispose_";
4592 ByrefType += utostr(flag);
4593 }
4594 ByrefType += "};\n";
4595 unsigned nameSize = Name.size();
4596 // for block or function pointer declaration. Name is aleady
4597 // part of the declaration.
4598 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4599 nameSize = 1;
4600 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4601 }
4602 else {
4603 SourceLocation startLoc;
4604 Expr *E = ND->getInit();
4605 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4606 startLoc = ECE->getLParenLoc();
4607 else
4608 startLoc = E->getLocStart();
4609 startLoc = SM->getExpansionLoc(startLoc);
4610 endBuf = SM->getCharacterData(startLoc);
4611 ByrefType += " " + Name;
4612 ByrefType += " = {(void*)";
4613 ByrefType += utostr(isa);
4614 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4615 ByrefType += utostr(flags);
4616 ByrefType += ", ";
4617 ByrefType += "sizeof(";
4618 RewriteByRefString(ByrefType, Name, ND);
4619 ByrefType += "), ";
4620 if (HasCopyAndDispose) {
4621 ByrefType += "__Block_byref_id_object_copy_";
4622 ByrefType += utostr(flag);
4623 ByrefType += ", __Block_byref_id_object_dispose_";
4624 ByrefType += utostr(flag);
4625 ByrefType += ", ";
4626 }
4627 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4628
4629 // Complete the newly synthesized compound expression by inserting a right
4630 // curly brace before the end of the declaration.
4631 // FIXME: This approach avoids rewriting the initializer expression. It
4632 // also assumes there is only one declarator. For example, the following
4633 // isn't currently supported by this routine (in general):
4634 //
4635 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4636 //
4637 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4638 const char *semiBuf = strchr(startInitializerBuf, ';');
4639 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4640 SourceLocation semiLoc =
4641 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4642
4643 InsertText(semiLoc, "}");
4644 }
4645 return;
4646}
4647
4648void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4649 // Add initializers for any closure decl refs.
4650 GetBlockDeclRefExprs(Exp->getBody());
4651 if (BlockDeclRefs.size()) {
4652 // Unique all "by copy" declarations.
4653 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004654 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004655 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4656 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4657 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4658 }
4659 }
4660 // Unique all "by ref" declarations.
4661 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004662 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004663 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4664 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4665 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4666 }
4667 }
4668 // Find any imported blocks...they will need special attention.
4669 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004670 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004671 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4672 BlockDeclRefs[i]->getType()->isBlockPointerType())
4673 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4674 }
4675}
4676
4677FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4678 IdentifierInfo *ID = &Context->Idents.get(name);
4679 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4680 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4681 SourceLocation(), ID, FType, 0, SC_Extern,
4682 SC_None, false, false);
4683}
4684
4685Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004686 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004687
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004688 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004689
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004690 Blocks.push_back(Exp);
4691
4692 CollectBlockDeclRefInfo(Exp);
4693
4694 // Add inner imported variables now used in current block.
4695 int countOfInnerDecls = 0;
4696 if (!InnerBlockDeclRefs.empty()) {
4697 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004698 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004699 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004700 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004701 // We need to save the copied-in variables in nested
4702 // blocks because it is needed at the end for some of the API generations.
4703 // See SynthesizeBlockLiterals routine.
4704 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4705 BlockDeclRefs.push_back(Exp);
4706 BlockByCopyDeclsPtrSet.insert(VD);
4707 BlockByCopyDecls.push_back(VD);
4708 }
John McCallf4b88a42012-03-10 09:33:50 +00004709 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004710 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4711 BlockDeclRefs.push_back(Exp);
4712 BlockByRefDeclsPtrSet.insert(VD);
4713 BlockByRefDecls.push_back(VD);
4714 }
4715 }
4716 // Find any imported blocks...they will need special attention.
4717 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004718 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004719 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4720 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4721 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4722 }
4723 InnerDeclRefsCount.push_back(countOfInnerDecls);
4724
4725 std::string FuncName;
4726
4727 if (CurFunctionDef)
4728 FuncName = CurFunctionDef->getNameAsString();
4729 else if (CurMethodDef)
4730 BuildUniqueMethodName(FuncName, CurMethodDef);
4731 else if (GlobalVarDecl)
4732 FuncName = std::string(GlobalVarDecl->getNameAsString());
4733
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004734 bool GlobalBlockExpr =
4735 block->getDeclContext()->getRedeclContext()->isFileContext();
4736
4737 if (GlobalBlockExpr && !GlobalVarDecl) {
4738 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4739 GlobalBlockExpr = false;
4740 }
4741
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004742 std::string BlockNumber = utostr(Blocks.size()-1);
4743
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004744 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4745
4746 // Get a pointer to the function type so we can cast appropriately.
4747 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4748 QualType FType = Context->getPointerType(BFT);
4749
4750 FunctionDecl *FD;
4751 Expr *NewRep;
4752
4753 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004754 std::string Tag;
4755
4756 if (GlobalBlockExpr)
4757 Tag = "__global_";
4758 else
4759 Tag = "__";
4760 Tag += FuncName + "_block_impl_" + BlockNumber;
4761
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004762 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004763 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004764 SourceLocation());
4765
4766 SmallVector<Expr*, 4> InitExprs;
4767
4768 // Initialize the block function.
4769 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004770 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4771 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004772 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4773 CK_BitCast, Arg);
4774 InitExprs.push_back(castExpr);
4775
4776 // Initialize the block descriptor.
4777 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4778
4779 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4780 SourceLocation(), SourceLocation(),
4781 &Context->Idents.get(DescData.c_str()),
4782 Context->VoidPtrTy, 0,
4783 SC_Static, SC_None);
4784 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004785 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004786 Context->VoidPtrTy,
4787 VK_LValue,
4788 SourceLocation()),
4789 UO_AddrOf,
4790 Context->getPointerType(Context->VoidPtrTy),
4791 VK_RValue, OK_Ordinary,
4792 SourceLocation());
4793 InitExprs.push_back(DescRefExpr);
4794
4795 // Add initializers for any closure decl refs.
4796 if (BlockDeclRefs.size()) {
4797 Expr *Exp;
4798 // Output all "by copy" declarations.
4799 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4800 E = BlockByCopyDecls.end(); I != E; ++I) {
4801 if (isObjCType((*I)->getType())) {
4802 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4803 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004804 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4805 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004806 if (HasLocalVariableExternalStorage(*I)) {
4807 QualType QT = (*I)->getType();
4808 QT = Context->getPointerType(QT);
4809 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4810 OK_Ordinary, SourceLocation());
4811 }
4812 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4813 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004814 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4815 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004816 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4817 CK_BitCast, Arg);
4818 } else {
4819 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004820 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4821 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004822 if (HasLocalVariableExternalStorage(*I)) {
4823 QualType QT = (*I)->getType();
4824 QT = Context->getPointerType(QT);
4825 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4826 OK_Ordinary, SourceLocation());
4827 }
4828
4829 }
4830 InitExprs.push_back(Exp);
4831 }
4832 // Output all "by ref" declarations.
4833 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4834 E = BlockByRefDecls.end(); I != E; ++I) {
4835 ValueDecl *ND = (*I);
4836 std::string Name(ND->getNameAsString());
4837 std::string RecName;
4838 RewriteByRefString(RecName, Name, ND, true);
4839 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4840 + sizeof("struct"));
4841 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4842 SourceLocation(), SourceLocation(),
4843 II);
4844 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4845 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4846
4847 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004848 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004849 SourceLocation());
4850 bool isNestedCapturedVar = false;
4851 if (block)
4852 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4853 ce = block->capture_end(); ci != ce; ++ci) {
4854 const VarDecl *variable = ci->getVariable();
4855 if (variable == ND && ci->isNested()) {
4856 assert (ci->isByRef() &&
4857 "SynthBlockInitExpr - captured block variable is not byref");
4858 isNestedCapturedVar = true;
4859 break;
4860 }
4861 }
4862 // captured nested byref variable has its address passed. Do not take
4863 // its address again.
4864 if (!isNestedCapturedVar)
4865 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4866 Context->getPointerType(Exp->getType()),
4867 VK_RValue, OK_Ordinary, SourceLocation());
4868 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4869 InitExprs.push_back(Exp);
4870 }
4871 }
4872 if (ImportedBlockDecls.size()) {
4873 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4874 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4875 unsigned IntSize =
4876 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4877 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4878 Context->IntTy, SourceLocation());
4879 InitExprs.push_back(FlagExp);
4880 }
4881 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4882 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004883
4884 if (GlobalBlockExpr) {
4885 assert (GlobalConstructionExp == 0 &&
4886 "SynthBlockInitExpr - GlobalConstructionExp must be null");
4887 GlobalConstructionExp = NewRep;
4888 NewRep = DRE;
4889 }
4890
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004891 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4892 Context->getPointerType(NewRep->getType()),
4893 VK_RValue, OK_Ordinary, SourceLocation());
4894 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4895 NewRep);
4896 BlockDeclRefs.clear();
4897 BlockByRefDecls.clear();
4898 BlockByRefDeclsPtrSet.clear();
4899 BlockByCopyDecls.clear();
4900 BlockByCopyDeclsPtrSet.clear();
4901 ImportedBlockDecls.clear();
4902 return NewRep;
4903}
4904
4905bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4906 if (const ObjCForCollectionStmt * CS =
4907 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4908 return CS->getElement() == DS;
4909 return false;
4910}
4911
4912//===----------------------------------------------------------------------===//
4913// Function Body / Expression rewriting
4914//===----------------------------------------------------------------------===//
4915
4916Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4917 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4918 isa<DoStmt>(S) || isa<ForStmt>(S))
4919 Stmts.push_back(S);
4920 else if (isa<ObjCForCollectionStmt>(S)) {
4921 Stmts.push_back(S);
4922 ObjCBcLabelNo.push_back(++BcLabelCount);
4923 }
4924
4925 // Pseudo-object operations and ivar references need special
4926 // treatment because we're going to recursively rewrite them.
4927 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4928 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4929 return RewritePropertyOrImplicitSetter(PseudoOp);
4930 } else {
4931 return RewritePropertyOrImplicitGetter(PseudoOp);
4932 }
4933 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4934 return RewriteObjCIvarRefExpr(IvarRefExpr);
4935 }
4936
4937 SourceRange OrigStmtRange = S->getSourceRange();
4938
4939 // Perform a bottom up rewrite of all children.
4940 for (Stmt::child_range CI = S->children(); CI; ++CI)
4941 if (*CI) {
4942 Stmt *childStmt = (*CI);
4943 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4944 if (newStmt) {
4945 *CI = newStmt;
4946 }
4947 }
4948
4949 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004950 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004951 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4952 InnerContexts.insert(BE->getBlockDecl());
4953 ImportedLocalExternalDecls.clear();
4954 GetInnerBlockDeclRefExprs(BE->getBody(),
4955 InnerBlockDeclRefs, InnerContexts);
4956 // Rewrite the block body in place.
4957 Stmt *SaveCurrentBody = CurrentBody;
4958 CurrentBody = BE->getBody();
4959 PropParentMap = 0;
4960 // block literal on rhs of a property-dot-sytax assignment
4961 // must be replaced by its synthesize ast so getRewrittenText
4962 // works as expected. In this case, what actually ends up on RHS
4963 // is the blockTranscribed which is the helper function for the
4964 // block literal; as in: self.c = ^() {[ace ARR];};
4965 bool saveDisableReplaceStmt = DisableReplaceStmt;
4966 DisableReplaceStmt = false;
4967 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4968 DisableReplaceStmt = saveDisableReplaceStmt;
4969 CurrentBody = SaveCurrentBody;
4970 PropParentMap = 0;
4971 ImportedLocalExternalDecls.clear();
4972 // Now we snarf the rewritten text and stash it away for later use.
4973 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4974 RewrittenBlockExprs[BE] = Str;
4975
4976 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4977
4978 //blockTranscribed->dump();
4979 ReplaceStmt(S, blockTranscribed);
4980 return blockTranscribed;
4981 }
4982 // Handle specific things.
4983 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4984 return RewriteAtEncode(AtEncode);
4985
4986 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4987 return RewriteAtSelector(AtSelector);
4988
4989 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4990 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00004991
4992 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
4993 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00004994
4995 if (ObjCNumericLiteral *NumericLitExpr = dyn_cast<ObjCNumericLiteral>(S))
4996 return RewriteObjCNumericLiteralExpr(NumericLitExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00004997
4998 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
4999 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005000
5001 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5002#if 0
5003 // Before we rewrite it, put the original message expression in a comment.
5004 SourceLocation startLoc = MessExpr->getLocStart();
5005 SourceLocation endLoc = MessExpr->getLocEnd();
5006
5007 const char *startBuf = SM->getCharacterData(startLoc);
5008 const char *endBuf = SM->getCharacterData(endLoc);
5009
5010 std::string messString;
5011 messString += "// ";
5012 messString.append(startBuf, endBuf-startBuf+1);
5013 messString += "\n";
5014
5015 // FIXME: Missing definition of
5016 // InsertText(clang::SourceLocation, char const*, unsigned int).
5017 // InsertText(startLoc, messString.c_str(), messString.size());
5018 // Tried this, but it didn't work either...
5019 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5020#endif
5021 return RewriteMessageExpr(MessExpr);
5022 }
5023
5024 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5025 return RewriteObjCTryStmt(StmtTry);
5026
5027 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5028 return RewriteObjCSynchronizedStmt(StmtTry);
5029
5030 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5031 return RewriteObjCThrowStmt(StmtThrow);
5032
5033 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5034 return RewriteObjCProtocolExpr(ProtocolExp);
5035
5036 if (ObjCForCollectionStmt *StmtForCollection =
5037 dyn_cast<ObjCForCollectionStmt>(S))
5038 return RewriteObjCForCollectionStmt(StmtForCollection,
5039 OrigStmtRange.getEnd());
5040 if (BreakStmt *StmtBreakStmt =
5041 dyn_cast<BreakStmt>(S))
5042 return RewriteBreakStmt(StmtBreakStmt);
5043 if (ContinueStmt *StmtContinueStmt =
5044 dyn_cast<ContinueStmt>(S))
5045 return RewriteContinueStmt(StmtContinueStmt);
5046
5047 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5048 // and cast exprs.
5049 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5050 // FIXME: What we're doing here is modifying the type-specifier that
5051 // precedes the first Decl. In the future the DeclGroup should have
5052 // a separate type-specifier that we can rewrite.
5053 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5054 // the context of an ObjCForCollectionStmt. For example:
5055 // NSArray *someArray;
5056 // for (id <FooProtocol> index in someArray) ;
5057 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5058 // and it depends on the original text locations/positions.
5059 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5060 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5061
5062 // Blocks rewrite rules.
5063 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5064 DI != DE; ++DI) {
5065 Decl *SD = *DI;
5066 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5067 if (isTopLevelBlockPointerType(ND->getType()))
5068 RewriteBlockPointerDecl(ND);
5069 else if (ND->getType()->isFunctionPointerType())
5070 CheckFunctionPointerDecl(ND->getType(), ND);
5071 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5072 if (VD->hasAttr<BlocksAttr>()) {
5073 static unsigned uniqueByrefDeclCount = 0;
5074 assert(!BlockByRefDeclNo.count(ND) &&
5075 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5076 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5077 RewriteByRefVar(VD);
5078 }
5079 else
5080 RewriteTypeOfDecl(VD);
5081 }
5082 }
5083 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5084 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5085 RewriteBlockPointerDecl(TD);
5086 else if (TD->getUnderlyingType()->isFunctionPointerType())
5087 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5088 }
5089 }
5090 }
5091
5092 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5093 RewriteObjCQualifiedInterfaceTypes(CE);
5094
5095 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5096 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5097 assert(!Stmts.empty() && "Statement stack is empty");
5098 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5099 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5100 && "Statement stack mismatch");
5101 Stmts.pop_back();
5102 }
5103 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005104 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5105 ValueDecl *VD = DRE->getDecl();
5106 if (VD->hasAttr<BlocksAttr>())
5107 return RewriteBlockDeclRefExpr(DRE);
5108 if (HasLocalVariableExternalStorage(VD))
5109 return RewriteLocalVariableExternalStorage(DRE);
5110 }
5111
5112 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5113 if (CE->getCallee()->getType()->isBlockPointerType()) {
5114 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5115 ReplaceStmt(S, BlockCall);
5116 return BlockCall;
5117 }
5118 }
5119 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5120 RewriteCastExpr(CE);
5121 }
5122#if 0
5123 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5124 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5125 ICE->getSubExpr(),
5126 SourceLocation());
5127 // Get the new text.
5128 std::string SStr;
5129 llvm::raw_string_ostream Buf(SStr);
5130 Replacement->printPretty(Buf, *Context);
5131 const std::string &Str = Buf.str();
5132
5133 printf("CAST = %s\n", &Str[0]);
5134 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5135 delete S;
5136 return Replacement;
5137 }
5138#endif
5139 // Return this stmt unmodified.
5140 return S;
5141}
5142
5143void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5144 for (RecordDecl::field_iterator i = RD->field_begin(),
5145 e = RD->field_end(); i != e; ++i) {
5146 FieldDecl *FD = *i;
5147 if (isTopLevelBlockPointerType(FD->getType()))
5148 RewriteBlockPointerDecl(FD);
5149 if (FD->getType()->isObjCQualifiedIdType() ||
5150 FD->getType()->isObjCQualifiedInterfaceType())
5151 RewriteObjCQualifiedInterfaceTypes(FD);
5152 }
5153}
5154
5155/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5156/// main file of the input.
5157void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5158 switch (D->getKind()) {
5159 case Decl::Function: {
5160 FunctionDecl *FD = cast<FunctionDecl>(D);
5161 if (FD->isOverloadedOperator())
5162 return;
5163
5164 // Since function prototypes don't have ParmDecl's, we check the function
5165 // prototype. This enables us to rewrite function declarations and
5166 // definitions using the same code.
5167 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5168
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005169 if (!FD->isThisDeclarationADefinition())
5170 break;
5171
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005172 // FIXME: If this should support Obj-C++, support CXXTryStmt
5173 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5174 CurFunctionDef = FD;
5175 CurFunctionDeclToDeclareForBlock = FD;
5176 CurrentBody = Body;
5177 Body =
5178 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5179 FD->setBody(Body);
5180 CurrentBody = 0;
5181 if (PropParentMap) {
5182 delete PropParentMap;
5183 PropParentMap = 0;
5184 }
5185 // This synthesizes and inserts the block "impl" struct, invoke function,
5186 // and any copy/dispose helper functions.
5187 InsertBlockLiteralsWithinFunction(FD);
5188 CurFunctionDef = 0;
5189 CurFunctionDeclToDeclareForBlock = 0;
5190 }
5191 break;
5192 }
5193 case Decl::ObjCMethod: {
5194 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5195 if (CompoundStmt *Body = MD->getCompoundBody()) {
5196 CurMethodDef = MD;
5197 CurrentBody = Body;
5198 Body =
5199 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5200 MD->setBody(Body);
5201 CurrentBody = 0;
5202 if (PropParentMap) {
5203 delete PropParentMap;
5204 PropParentMap = 0;
5205 }
5206 InsertBlockLiteralsWithinMethod(MD);
5207 CurMethodDef = 0;
5208 }
5209 break;
5210 }
5211 case Decl::ObjCImplementation: {
5212 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5213 ClassImplementation.push_back(CI);
5214 break;
5215 }
5216 case Decl::ObjCCategoryImpl: {
5217 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5218 CategoryImplementation.push_back(CI);
5219 break;
5220 }
5221 case Decl::Var: {
5222 VarDecl *VD = cast<VarDecl>(D);
5223 RewriteObjCQualifiedInterfaceTypes(VD);
5224 if (isTopLevelBlockPointerType(VD->getType()))
5225 RewriteBlockPointerDecl(VD);
5226 else if (VD->getType()->isFunctionPointerType()) {
5227 CheckFunctionPointerDecl(VD->getType(), VD);
5228 if (VD->getInit()) {
5229 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5230 RewriteCastExpr(CE);
5231 }
5232 }
5233 } else if (VD->getType()->isRecordType()) {
5234 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5235 if (RD->isCompleteDefinition())
5236 RewriteRecordBody(RD);
5237 }
5238 if (VD->getInit()) {
5239 GlobalVarDecl = VD;
5240 CurrentBody = VD->getInit();
5241 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5242 CurrentBody = 0;
5243 if (PropParentMap) {
5244 delete PropParentMap;
5245 PropParentMap = 0;
5246 }
5247 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5248 GlobalVarDecl = 0;
5249
5250 // This is needed for blocks.
5251 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5252 RewriteCastExpr(CE);
5253 }
5254 }
5255 break;
5256 }
5257 case Decl::TypeAlias:
5258 case Decl::Typedef: {
5259 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5260 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5261 RewriteBlockPointerDecl(TD);
5262 else if (TD->getUnderlyingType()->isFunctionPointerType())
5263 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5264 }
5265 break;
5266 }
5267 case Decl::CXXRecord:
5268 case Decl::Record: {
5269 RecordDecl *RD = cast<RecordDecl>(D);
5270 if (RD->isCompleteDefinition())
5271 RewriteRecordBody(RD);
5272 break;
5273 }
5274 default:
5275 break;
5276 }
5277 // Nothing yet.
5278}
5279
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005280/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5281/// protocol reference symbols in the for of:
5282/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5283static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5284 ObjCProtocolDecl *PDecl,
5285 std::string &Result) {
5286 // Also output .objc_protorefs$B section and its meta-data.
5287 if (Context->getLangOpts().MicrosoftExt)
5288 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5289 Result += "struct _protocol_t *";
5290 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5291 Result += PDecl->getNameAsString();
5292 Result += " = &";
5293 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5294 Result += ";\n";
5295}
5296
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005297void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5298 if (Diags.hasErrorOccurred())
5299 return;
5300
5301 RewriteInclude();
5302
5303 // Here's a great place to add any extra declarations that may be needed.
5304 // Write out meta data for each @protocol(<expr>).
5305 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005306 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005307 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005308 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5309 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005310
5311 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005312 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5313 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5314 // Write struct declaration for the class matching its ivar declarations.
5315 // Note that for modern abi, this is postponed until the end of TU
5316 // because class extensions and the implementation might declare their own
5317 // private ivars.
5318 RewriteInterfaceDecl(CDecl);
5319 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005320
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005321 if (ClassImplementation.size() || CategoryImplementation.size())
5322 RewriteImplementations();
5323
5324 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5325 // we are done.
5326 if (const RewriteBuffer *RewriteBuf =
5327 Rewrite.getRewriteBufferFor(MainFileID)) {
5328 //printf("Changed:\n");
5329 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5330 } else {
5331 llvm::errs() << "No changes\n";
5332 }
5333
5334 if (ClassImplementation.size() || CategoryImplementation.size() ||
5335 ProtocolExprDecls.size()) {
5336 // Rewrite Objective-c meta data*
5337 std::string ResultStr;
5338 RewriteMetaDataIntoBuffer(ResultStr);
5339 // Emit metadata.
5340 *OutFile << ResultStr;
5341 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005342 // Emit ImageInfo;
5343 {
5344 std::string ResultStr;
5345 WriteImageInfo(ResultStr);
5346 *OutFile << ResultStr;
5347 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005348 OutFile->flush();
5349}
5350
5351void RewriteModernObjC::Initialize(ASTContext &context) {
5352 InitializeCommon(context);
5353
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005354 Preamble += "#ifndef __OBJC2__\n";
5355 Preamble += "#define __OBJC2__\n";
5356 Preamble += "#endif\n";
5357
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005358 // declaring objc_selector outside the parameter list removes a silly
5359 // scope related warning...
5360 if (IsHeader)
5361 Preamble = "#pragma once\n";
5362 Preamble += "struct objc_selector; struct objc_class;\n";
5363 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5364 Preamble += "struct objc_object *superClass; ";
5365 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005366 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005367 // These are currently generated.
5368 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005369 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005370 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5371 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005372 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5373 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005374 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005375 // These are generated but not necessary for functionality.
5376 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5377 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005378 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5379 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005380 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005381
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005382 // These need be generated for performance. Currently they are not,
5383 // using API calls instead.
5384 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5385 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5386 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5387
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005388 // Add a constructor for creating temporary objects.
5389 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5390 ": ";
5391 Preamble += "object(o), superClass(s) {} ";
5392 }
5393 Preamble += "};\n";
5394 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5395 Preamble += "typedef struct objc_object Protocol;\n";
5396 Preamble += "#define _REWRITER_typedef_Protocol\n";
5397 Preamble += "#endif\n";
5398 if (LangOpts.MicrosoftExt) {
5399 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5400 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005401 }
5402 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005403 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005404
5405 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5406 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5407 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5408 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5409 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5410
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005411 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5412 Preamble += "(const char *);\n";
5413 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5414 Preamble += "(struct objc_class *);\n";
5415 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5416 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005417 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005418 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005419 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5420 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005421 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5422 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5423 Preamble += "struct __objcFastEnumerationState {\n\t";
5424 Preamble += "unsigned long state;\n\t";
5425 Preamble += "void **itemsPtr;\n\t";
5426 Preamble += "unsigned long *mutationsPtr;\n\t";
5427 Preamble += "unsigned long extra[5];\n};\n";
5428 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5429 Preamble += "#define __FASTENUMERATIONSTATE\n";
5430 Preamble += "#endif\n";
5431 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5432 Preamble += "struct __NSConstantStringImpl {\n";
5433 Preamble += " int *isa;\n";
5434 Preamble += " int flags;\n";
5435 Preamble += " char *str;\n";
5436 Preamble += " long length;\n";
5437 Preamble += "};\n";
5438 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5439 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5440 Preamble += "#else\n";
5441 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5442 Preamble += "#endif\n";
5443 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5444 Preamble += "#endif\n";
5445 // Blocks preamble.
5446 Preamble += "#ifndef BLOCK_IMPL\n";
5447 Preamble += "#define BLOCK_IMPL\n";
5448 Preamble += "struct __block_impl {\n";
5449 Preamble += " void *isa;\n";
5450 Preamble += " int Flags;\n";
5451 Preamble += " int Reserved;\n";
5452 Preamble += " void *FuncPtr;\n";
5453 Preamble += "};\n";
5454 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5455 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5456 Preamble += "extern \"C\" __declspec(dllexport) "
5457 "void _Block_object_assign(void *, const void *, const int);\n";
5458 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5459 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5460 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5461 Preamble += "#else\n";
5462 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5463 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5464 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5465 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5466 Preamble += "#endif\n";
5467 Preamble += "#endif\n";
5468 if (LangOpts.MicrosoftExt) {
5469 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5470 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5471 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5472 Preamble += "#define __attribute__(X)\n";
5473 Preamble += "#endif\n";
5474 Preamble += "#define __weak\n";
5475 }
5476 else {
5477 Preamble += "#define __block\n";
5478 Preamble += "#define __weak\n";
5479 }
5480 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5481 // as this avoids warning in any 64bit/32bit compilation model.
5482 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5483}
5484
5485/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5486/// ivar offset.
5487void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5488 std::string &Result) {
5489 if (ivar->isBitField()) {
5490 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5491 // place all bitfields at offset 0.
5492 Result += "0";
5493 } else {
5494 Result += "__OFFSETOFIVAR__(struct ";
5495 Result += ivar->getContainingInterface()->getNameAsString();
5496 if (LangOpts.MicrosoftExt)
5497 Result += "_IMPL";
5498 Result += ", ";
5499 Result += ivar->getNameAsString();
5500 Result += ")";
5501 }
5502}
5503
5504/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5505/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005506/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005507/// char *attributes;
5508/// }
5509
5510/// struct _prop_list_t {
5511/// uint32_t entsize; // sizeof(struct _prop_t)
5512/// uint32_t count_of_properties;
5513/// struct _prop_t prop_list[count_of_properties];
5514/// }
5515
5516/// struct _protocol_t;
5517
5518/// struct _protocol_list_t {
5519/// long protocol_count; // Note, this is 32/64 bit
5520/// struct _protocol_t * protocol_list[protocol_count];
5521/// }
5522
5523/// struct _objc_method {
5524/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005525/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005526/// char *_imp;
5527/// }
5528
5529/// struct _method_list_t {
5530/// uint32_t entsize; // sizeof(struct _objc_method)
5531/// uint32_t method_count;
5532/// struct _objc_method method_list[method_count];
5533/// }
5534
5535/// struct _protocol_t {
5536/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005537/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005538/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005539/// const struct method_list_t *instance_methods;
5540/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005541/// const struct method_list_t *optionalInstanceMethods;
5542/// const struct method_list_t *optionalClassMethods;
5543/// const struct _prop_list_t * properties;
5544/// const uint32_t size; // sizeof(struct _protocol_t)
5545/// const uint32_t flags; // = 0
5546/// const char ** extendedMethodTypes;
5547/// }
5548
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005549/// struct _ivar_t {
5550/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005551/// const char *name;
5552/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005553/// uint32_t alignment;
5554/// uint32_t size;
5555/// }
5556
5557/// struct _ivar_list_t {
5558/// uint32 entsize; // sizeof(struct _ivar_t)
5559/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005560/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005561/// }
5562
5563/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005564/// uint32_t flags;
5565/// uint32_t instanceStart;
5566/// uint32_t instanceSize;
5567/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005568/// const uint8_t *ivarLayout;
5569/// const char *name;
5570/// const struct _method_list_t *baseMethods;
5571/// const struct _protocol_list_t *baseProtocols;
5572/// const struct _ivar_list_t *ivars;
5573/// const uint8_t *weakIvarLayout;
5574/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005575/// }
5576
5577/// struct _class_t {
5578/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005579/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005580/// void *cache;
5581/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005582/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005583/// }
5584
5585/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005586/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005587/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005588/// const struct _method_list_t *instance_methods;
5589/// const struct _method_list_t *class_methods;
5590/// const struct _protocol_list_t *protocols;
5591/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005592/// }
5593
5594/// MessageRefTy - LLVM for:
5595/// struct _message_ref_t {
5596/// IMP messenger;
5597/// SEL name;
5598/// };
5599
5600/// SuperMessageRefTy - LLVM for:
5601/// struct _super_message_ref_t {
5602/// SUPER_IMP messenger;
5603/// SEL name;
5604/// };
5605
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005606static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005607 static bool meta_data_declared = false;
5608 if (meta_data_declared)
5609 return;
5610
5611 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005612 Result += "\tconst char *name;\n";
5613 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005614 Result += "};\n";
5615
5616 Result += "\nstruct _protocol_t;\n";
5617
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005618 Result += "\nstruct _objc_method {\n";
5619 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005620 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005621 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005622 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005623
5624 Result += "\nstruct _protocol_t {\n";
5625 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005626 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005627 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005628 Result += "\tconst struct method_list_t *instance_methods;\n";
5629 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005630 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5631 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5632 Result += "\tconst struct _prop_list_t * properties;\n";
5633 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5634 Result += "\tconst unsigned int flags; // = 0\n";
5635 Result += "\tconst char ** extendedMethodTypes;\n";
5636 Result += "};\n";
5637
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005638 Result += "\nstruct _ivar_t {\n";
5639 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005640 Result += "\tconst char *name;\n";
5641 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005642 Result += "\tunsigned int alignment;\n";
5643 Result += "\tunsigned int size;\n";
5644 Result += "};\n";
5645
5646 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005647 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005648 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005649 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005650 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5651 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005652 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005653 Result += "\tconst unsigned char *ivarLayout;\n";
5654 Result += "\tconst char *name;\n";
5655 Result += "\tconst struct _method_list_t *baseMethods;\n";
5656 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5657 Result += "\tconst struct _ivar_list_t *ivars;\n";
5658 Result += "\tconst unsigned char *weakIvarLayout;\n";
5659 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005660 Result += "};\n";
5661
5662 Result += "\nstruct _class_t {\n";
5663 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005664 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005665 Result += "\tvoid *cache;\n";
5666 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005667 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005668 Result += "};\n";
5669
5670 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005671 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005672 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005673 Result += "\tconst struct _method_list_t *instance_methods;\n";
5674 Result += "\tconst struct _method_list_t *class_methods;\n";
5675 Result += "\tconst struct _protocol_list_t *protocols;\n";
5676 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005677 Result += "};\n";
5678
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005679 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005680 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005681 meta_data_declared = true;
5682}
5683
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005684static void Write_protocol_list_t_TypeDecl(std::string &Result,
5685 long super_protocol_count) {
5686 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5687 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5688 Result += "\tstruct _protocol_t *super_protocols[";
5689 Result += utostr(super_protocol_count); Result += "];\n";
5690 Result += "}";
5691}
5692
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005693static void Write_method_list_t_TypeDecl(std::string &Result,
5694 unsigned int method_count) {
5695 Result += "struct /*_method_list_t*/"; Result += " {\n";
5696 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5697 Result += "\tunsigned int method_count;\n";
5698 Result += "\tstruct _objc_method method_list[";
5699 Result += utostr(method_count); Result += "];\n";
5700 Result += "}";
5701}
5702
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005703static void Write__prop_list_t_TypeDecl(std::string &Result,
5704 unsigned int property_count) {
5705 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5706 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5707 Result += "\tunsigned int count_of_properties;\n";
5708 Result += "\tstruct _prop_t prop_list[";
5709 Result += utostr(property_count); Result += "];\n";
5710 Result += "}";
5711}
5712
Fariborz Jahanianae932952012-02-10 20:47:10 +00005713static void Write__ivar_list_t_TypeDecl(std::string &Result,
5714 unsigned int ivar_count) {
5715 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5716 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5717 Result += "\tunsigned int count;\n";
5718 Result += "\tstruct _ivar_t ivar_list[";
5719 Result += utostr(ivar_count); Result += "];\n";
5720 Result += "}";
5721}
5722
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005723static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5724 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5725 StringRef VarName,
5726 StringRef ProtocolName) {
5727 if (SuperProtocols.size() > 0) {
5728 Result += "\nstatic ";
5729 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5730 Result += " "; Result += VarName;
5731 Result += ProtocolName;
5732 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5733 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5734 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5735 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5736 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5737 Result += SuperPD->getNameAsString();
5738 if (i == e-1)
5739 Result += "\n};\n";
5740 else
5741 Result += ",\n";
5742 }
5743 }
5744}
5745
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005746static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5747 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005748 ArrayRef<ObjCMethodDecl *> Methods,
5749 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005750 StringRef TopLevelDeclName,
5751 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005752 if (Methods.size() > 0) {
5753 Result += "\nstatic ";
5754 Write_method_list_t_TypeDecl(Result, Methods.size());
5755 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005756 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005757 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5758 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5759 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5760 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5761 ObjCMethodDecl *MD = Methods[i];
5762 if (i == 0)
5763 Result += "\t{{(struct objc_selector *)\"";
5764 else
5765 Result += "\t{(struct objc_selector *)\"";
5766 Result += (MD)->getSelector().getAsString(); Result += "\"";
5767 Result += ", ";
5768 std::string MethodTypeString;
5769 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5770 Result += "\""; Result += MethodTypeString; Result += "\"";
5771 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005772 if (!MethodImpl)
5773 Result += "0";
5774 else {
5775 Result += "(void *)";
5776 Result += RewriteObj.MethodInternalNames[MD];
5777 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005778 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005779 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005780 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005781 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005782 }
5783 Result += "};\n";
5784 }
5785}
5786
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005787static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005788 ASTContext *Context, std::string &Result,
5789 ArrayRef<ObjCPropertyDecl *> Properties,
5790 const Decl *Container,
5791 StringRef VarName,
5792 StringRef ProtocolName) {
5793 if (Properties.size() > 0) {
5794 Result += "\nstatic ";
5795 Write__prop_list_t_TypeDecl(Result, Properties.size());
5796 Result += " "; Result += VarName;
5797 Result += ProtocolName;
5798 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5799 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5800 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5801 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5802 ObjCPropertyDecl *PropDecl = Properties[i];
5803 if (i == 0)
5804 Result += "\t{{\"";
5805 else
5806 Result += "\t{\"";
5807 Result += PropDecl->getName(); Result += "\",";
5808 std::string PropertyTypeString, QuotePropertyTypeString;
5809 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5810 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5811 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5812 if (i == e-1)
5813 Result += "}}\n";
5814 else
5815 Result += "},\n";
5816 }
5817 Result += "};\n";
5818 }
5819}
5820
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005821// Metadata flags
5822enum MetaDataDlags {
5823 CLS = 0x0,
5824 CLS_META = 0x1,
5825 CLS_ROOT = 0x2,
5826 OBJC2_CLS_HIDDEN = 0x10,
5827 CLS_EXCEPTION = 0x20,
5828
5829 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5830 CLS_HAS_IVAR_RELEASER = 0x40,
5831 /// class was compiled with -fobjc-arr
5832 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5833};
5834
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005835static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5836 unsigned int flags,
5837 const std::string &InstanceStart,
5838 const std::string &InstanceSize,
5839 ArrayRef<ObjCMethodDecl *>baseMethods,
5840 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5841 ArrayRef<ObjCIvarDecl *>ivars,
5842 ArrayRef<ObjCPropertyDecl *>Properties,
5843 StringRef VarName,
5844 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005845 Result += "\nstatic struct _class_ro_t ";
5846 Result += VarName; Result += ClassName;
5847 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5848 Result += "\t";
5849 Result += llvm::utostr(flags); Result += ", ";
5850 Result += InstanceStart; Result += ", ";
5851 Result += InstanceSize; Result += ", \n";
5852 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005853 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5854 if (Triple.getArch() == llvm::Triple::x86_64)
5855 // uint32_t const reserved; // only when building for 64bit targets
5856 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005857 // const uint8_t * const ivarLayout;
5858 Result += "0, \n\t";
5859 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005860 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005861 if (baseMethods.size() > 0) {
5862 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005863 if (metaclass)
5864 Result += "_OBJC_$_CLASS_METHODS_";
5865 else
5866 Result += "_OBJC_$_INSTANCE_METHODS_";
5867 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005868 Result += ",\n\t";
5869 }
5870 else
5871 Result += "0, \n\t";
5872
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005873 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005874 Result += "(const struct _objc_protocol_list *)&";
5875 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5876 Result += ",\n\t";
5877 }
5878 else
5879 Result += "0, \n\t";
5880
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005881 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005882 Result += "(const struct _ivar_list_t *)&";
5883 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5884 Result += ",\n\t";
5885 }
5886 else
5887 Result += "0, \n\t";
5888
5889 // weakIvarLayout
5890 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005891 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005892 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005893 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005894 Result += ",\n";
5895 }
5896 else
5897 Result += "0, \n";
5898
5899 Result += "};\n";
5900}
5901
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005902static void Write_class_t(ASTContext *Context, std::string &Result,
5903 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005904 const ObjCInterfaceDecl *CDecl, bool metaclass) {
5905 bool rootClass = (!CDecl->getSuperClass());
5906 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005907
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005908 if (!rootClass) {
5909 // Find the Root class
5910 RootClass = CDecl->getSuperClass();
5911 while (RootClass->getSuperClass()) {
5912 RootClass = RootClass->getSuperClass();
5913 }
5914 }
5915
5916 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005917 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005918 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005919 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005920 if (CDecl->getImplementation())
5921 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005922 else
5923 Result += "__declspec(dllimport) ";
5924
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005925 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005926 Result += CDecl->getNameAsString();
5927 Result += ";\n";
5928 }
5929 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005930 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005931 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005932 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005933 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005934 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005935 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005936 else
5937 Result += "__declspec(dllimport) ";
5938
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005939 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005940 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005941 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005942 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005943
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005944 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005945 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005946 if (RootClass->getImplementation())
5947 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005948 else
5949 Result += "__declspec(dllimport) ";
5950
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005951 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005952 Result += VarName;
5953 Result += RootClass->getNameAsString();
5954 Result += ";\n";
5955 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005956 }
5957
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005958 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
5959 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005960 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5961 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005962 if (metaclass) {
5963 if (!rootClass) {
5964 Result += "0, // &"; Result += VarName;
5965 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005966 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005967 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005968 Result += CDecl->getSuperClass()->getNameAsString();
5969 Result += ",\n\t";
5970 }
5971 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005972 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005973 Result += CDecl->getNameAsString();
5974 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005975 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005976 Result += ",\n\t";
5977 }
5978 }
5979 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005980 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005981 Result += CDecl->getNameAsString();
5982 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005983 if (!rootClass) {
5984 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005985 Result += CDecl->getSuperClass()->getNameAsString();
5986 Result += ",\n\t";
5987 }
5988 else
5989 Result += "0,\n\t";
5990 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005991 Result += "0, // (void *)&_objc_empty_cache,\n\t";
5992 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
5993 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005994 Result += "&_OBJC_METACLASS_RO_$_";
5995 else
5996 Result += "&_OBJC_CLASS_RO_$_";
5997 Result += CDecl->getNameAsString();
5998 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005999
6000 // Add static function to initialize some of the meta-data fields.
6001 // avoid doing it twice.
6002 if (metaclass)
6003 return;
6004
6005 const ObjCInterfaceDecl *SuperClass =
6006 rootClass ? CDecl : CDecl->getSuperClass();
6007
6008 Result += "static void OBJC_CLASS_SETUP_$_";
6009 Result += CDecl->getNameAsString();
6010 Result += "(void ) {\n";
6011 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6012 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006013 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006014
6015 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006016 Result += ".superclass = ";
6017 if (rootClass)
6018 Result += "&OBJC_CLASS_$_";
6019 else
6020 Result += "&OBJC_METACLASS_$_";
6021
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006022 Result += SuperClass->getNameAsString(); Result += ";\n";
6023
6024 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6025 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6026
6027 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6028 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6029 Result += CDecl->getNameAsString(); Result += ";\n";
6030
6031 if (!rootClass) {
6032 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6033 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6034 Result += SuperClass->getNameAsString(); Result += ";\n";
6035 }
6036
6037 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6038 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6039 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006040}
6041
Fariborz Jahanian61186122012-02-17 18:40:41 +00006042static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6043 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006044 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006045 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006046 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6047 ArrayRef<ObjCMethodDecl *> ClassMethods,
6048 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6049 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006050 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006051 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006052 // must declare an extern class object in case this class is not implemented
6053 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006054 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006055 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006056 if (ClassDecl->getImplementation())
6057 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006058 else
6059 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006060
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006061 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006062 Result += "OBJC_CLASS_$_"; Result += ClassName;
6063 Result += ";\n";
6064
Fariborz Jahanian61186122012-02-17 18:40:41 +00006065 Result += "\nstatic struct _category_t ";
6066 Result += "_OBJC_$_CATEGORY_";
6067 Result += ClassName; Result += "_$_"; Result += CatName;
6068 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6069 Result += "{\n";
6070 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006071 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006072 Result += ",\n";
6073 if (InstanceMethods.size() > 0) {
6074 Result += "\t(const struct _method_list_t *)&";
6075 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6076 Result += ClassName; Result += "_$_"; Result += CatName;
6077 Result += ",\n";
6078 }
6079 else
6080 Result += "\t0,\n";
6081
6082 if (ClassMethods.size() > 0) {
6083 Result += "\t(const struct _method_list_t *)&";
6084 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6085 Result += ClassName; Result += "_$_"; Result += CatName;
6086 Result += ",\n";
6087 }
6088 else
6089 Result += "\t0,\n";
6090
6091 if (RefedProtocols.size() > 0) {
6092 Result += "\t(const struct _protocol_list_t *)&";
6093 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6094 Result += ClassName; Result += "_$_"; Result += CatName;
6095 Result += ",\n";
6096 }
6097 else
6098 Result += "\t0,\n";
6099
6100 if (ClassProperties.size() > 0) {
6101 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6102 Result += ClassName; Result += "_$_"; Result += CatName;
6103 Result += ",\n";
6104 }
6105 else
6106 Result += "\t0,\n";
6107
6108 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006109
6110 // Add static function to initialize the class pointer in the category structure.
6111 Result += "static void OBJC_CATEGORY_SETUP_$_";
6112 Result += ClassDecl->getNameAsString();
6113 Result += "_$_";
6114 Result += CatName;
6115 Result += "(void ) {\n";
6116 Result += "\t_OBJC_$_CATEGORY_";
6117 Result += ClassDecl->getNameAsString();
6118 Result += "_$_";
6119 Result += CatName;
6120 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6121 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006122}
6123
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006124static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6125 ASTContext *Context, std::string &Result,
6126 ArrayRef<ObjCMethodDecl *> Methods,
6127 StringRef VarName,
6128 StringRef ProtocolName) {
6129 if (Methods.size() == 0)
6130 return;
6131
6132 Result += "\nstatic const char *";
6133 Result += VarName; Result += ProtocolName;
6134 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6135 Result += "{\n";
6136 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6137 ObjCMethodDecl *MD = Methods[i];
6138 std::string MethodTypeString, QuoteMethodTypeString;
6139 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6140 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6141 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6142 if (i == e-1)
6143 Result += "\n};\n";
6144 else {
6145 Result += ",\n";
6146 }
6147 }
6148}
6149
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006150static void Write_IvarOffsetVar(ASTContext *Context,
6151 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006152 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006153 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006154 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6155 // this is what happens:
6156 /**
6157 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6158 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6159 Class->getVisibility() == HiddenVisibility)
6160 Visibility shoud be: HiddenVisibility;
6161 else
6162 Visibility shoud be: DefaultVisibility;
6163 */
6164
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006165 Result += "\n";
6166 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6167 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006168 if (Context->getLangOpts().MicrosoftExt)
6169 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6170
6171 if (!Context->getLangOpts().MicrosoftExt ||
6172 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006173 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006174 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006175 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006176 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006177 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006178 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6179 Result += " = ";
6180 if (IvarDecl->isBitField()) {
6181 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6182 // place all bitfields at offset 0.
6183 Result += "0;\n";
6184 }
6185 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006186 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006187 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006188 Result += "_IMPL, ";
6189 Result += IvarDecl->getName(); Result += ");\n";
6190 }
6191 }
6192}
6193
Fariborz Jahanianae932952012-02-10 20:47:10 +00006194static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6195 ASTContext *Context, std::string &Result,
6196 ArrayRef<ObjCIvarDecl *> Ivars,
6197 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006198 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006199 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006200 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006201
Fariborz Jahanianae932952012-02-10 20:47:10 +00006202 Result += "\nstatic ";
6203 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6204 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006205 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006206 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6207 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6208 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6209 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6210 ObjCIvarDecl *IvarDecl = Ivars[i];
6211 if (i == 0)
6212 Result += "\t{{";
6213 else
6214 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006215 Result += "(unsigned long int *)&";
6216 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006217 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006218
6219 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6220 std::string IvarTypeString, QuoteIvarTypeString;
6221 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6222 IvarDecl);
6223 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6224 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6225
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006226 // FIXME. this alignment represents the host alignment and need be changed to
6227 // represent the target alignment.
6228 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6229 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006230 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006231 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6232 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006233 if (i == e-1)
6234 Result += "}}\n";
6235 else
6236 Result += "},\n";
6237 }
6238 Result += "};\n";
6239 }
6240}
6241
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006242/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006243void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6244 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006245
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006246 // Do not synthesize the protocol more than once.
6247 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6248 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006249 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006250
6251 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6252 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006253 // Must write out all protocol definitions in current qualifier list,
6254 // and in their nested qualifiers before writing out current definition.
6255 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6256 E = PDecl->protocol_end(); I != E; ++I)
6257 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006258
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006259 // Construct method lists.
6260 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6261 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6262 for (ObjCProtocolDecl::instmeth_iterator
6263 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6264 I != E; ++I) {
6265 ObjCMethodDecl *MD = *I;
6266 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6267 OptInstanceMethods.push_back(MD);
6268 } else {
6269 InstanceMethods.push_back(MD);
6270 }
6271 }
6272
6273 for (ObjCProtocolDecl::classmeth_iterator
6274 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6275 I != E; ++I) {
6276 ObjCMethodDecl *MD = *I;
6277 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6278 OptClassMethods.push_back(MD);
6279 } else {
6280 ClassMethods.push_back(MD);
6281 }
6282 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006283 std::vector<ObjCMethodDecl *> AllMethods;
6284 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6285 AllMethods.push_back(InstanceMethods[i]);
6286 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6287 AllMethods.push_back(ClassMethods[i]);
6288 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6289 AllMethods.push_back(OptInstanceMethods[i]);
6290 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6291 AllMethods.push_back(OptClassMethods[i]);
6292
6293 Write__extendedMethodTypes_initializer(*this, Context, Result,
6294 AllMethods,
6295 "_OBJC_PROTOCOL_METHOD_TYPES_",
6296 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006297 // Protocol's super protocol list
6298 std::vector<ObjCProtocolDecl *> SuperProtocols;
6299 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6300 E = PDecl->protocol_end(); I != E; ++I)
6301 SuperProtocols.push_back(*I);
6302
6303 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6304 "_OBJC_PROTOCOL_REFS_",
6305 PDecl->getNameAsString());
6306
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006307 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006308 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006309 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006310
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006311 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006312 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006313 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006314
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006315 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006316 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006317 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006318
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006319 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006320 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006321 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006322
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006323 // Protocol's property metadata.
6324 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6325 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6326 E = PDecl->prop_end(); I != E; ++I)
6327 ProtocolProperties.push_back(*I);
6328
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006329 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006330 /* Container */0,
6331 "_OBJC_PROTOCOL_PROPERTIES_",
6332 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006333
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006334 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006335 Result += "\n";
6336 if (LangOpts.MicrosoftExt)
6337 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006338 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006339 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006340 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6341 Result += "\t0,\n"; // id is; is null
6342 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006343 if (SuperProtocols.size() > 0) {
6344 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6345 Result += PDecl->getNameAsString(); Result += ",\n";
6346 }
6347 else
6348 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006349 if (InstanceMethods.size() > 0) {
6350 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6351 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006352 }
6353 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006354 Result += "\t0,\n";
6355
6356 if (ClassMethods.size() > 0) {
6357 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6358 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006359 }
6360 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006361 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006362
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006363 if (OptInstanceMethods.size() > 0) {
6364 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6365 Result += PDecl->getNameAsString(); Result += ",\n";
6366 }
6367 else
6368 Result += "\t0,\n";
6369
6370 if (OptClassMethods.size() > 0) {
6371 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6372 Result += PDecl->getNameAsString(); Result += ",\n";
6373 }
6374 else
6375 Result += "\t0,\n";
6376
6377 if (ProtocolProperties.size() > 0) {
6378 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6379 Result += PDecl->getNameAsString(); Result += ",\n";
6380 }
6381 else
6382 Result += "\t0,\n";
6383
6384 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6385 Result += "\t0,\n";
6386
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006387 if (AllMethods.size() > 0) {
6388 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6389 Result += PDecl->getNameAsString();
6390 Result += "\n};\n";
6391 }
6392 else
6393 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006394
6395 // Use this protocol meta-data to build protocol list table in section
6396 // .objc_protolist$B
6397 // Unspecified visibility means 'private extern'.
6398 if (LangOpts.MicrosoftExt)
6399 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6400 Result += "struct _protocol_t *";
6401 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6402 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6403 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006404
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006405 // Mark this protocol as having been generated.
6406 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6407 llvm_unreachable("protocol already synthesized");
6408
6409}
6410
6411void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6412 const ObjCList<ObjCProtocolDecl> &Protocols,
6413 StringRef prefix, StringRef ClassName,
6414 std::string &Result) {
6415 if (Protocols.empty()) return;
6416
6417 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006418 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006419
6420 // Output the top lovel protocol meta-data for the class.
6421 /* struct _objc_protocol_list {
6422 struct _objc_protocol_list *next;
6423 int protocol_count;
6424 struct _objc_protocol *class_protocols[];
6425 }
6426 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006427 Result += "\n";
6428 if (LangOpts.MicrosoftExt)
6429 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6430 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006431 Result += "\tstruct _objc_protocol_list *next;\n";
6432 Result += "\tint protocol_count;\n";
6433 Result += "\tstruct _objc_protocol *class_protocols[";
6434 Result += utostr(Protocols.size());
6435 Result += "];\n} _OBJC_";
6436 Result += prefix;
6437 Result += "_PROTOCOLS_";
6438 Result += ClassName;
6439 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6440 "{\n\t0, ";
6441 Result += utostr(Protocols.size());
6442 Result += "\n";
6443
6444 Result += "\t,{&_OBJC_PROTOCOL_";
6445 Result += Protocols[0]->getNameAsString();
6446 Result += " \n";
6447
6448 for (unsigned i = 1; i != Protocols.size(); i++) {
6449 Result += "\t ,&_OBJC_PROTOCOL_";
6450 Result += Protocols[i]->getNameAsString();
6451 Result += "\n";
6452 }
6453 Result += "\t }\n};\n";
6454}
6455
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006456/// hasObjCExceptionAttribute - Return true if this class or any super
6457/// class has the __objc_exception__ attribute.
6458/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6459static bool hasObjCExceptionAttribute(ASTContext &Context,
6460 const ObjCInterfaceDecl *OID) {
6461 if (OID->hasAttr<ObjCExceptionAttr>())
6462 return true;
6463 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6464 return hasObjCExceptionAttribute(Context, Super);
6465 return false;
6466}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006467
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006468void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6469 std::string &Result) {
6470 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6471
6472 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006473 if (CDecl->isImplicitInterfaceDecl())
6474 assert(false &&
6475 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006476
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006477 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006478 SmallVector<ObjCIvarDecl *, 8> IVars;
6479
6480 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6481 IVD; IVD = IVD->getNextIvar()) {
6482 // Ignore unnamed bit-fields.
6483 if (!IVD->getDeclName())
6484 continue;
6485 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006486 }
6487
Fariborz Jahanianae932952012-02-10 20:47:10 +00006488 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006489 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006490 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006491
6492 // Build _objc_method_list for class's instance methods if needed
6493 SmallVector<ObjCMethodDecl *, 32>
6494 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6495
6496 // If any of our property implementations have associated getters or
6497 // setters, produce metadata for them as well.
6498 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6499 PropEnd = IDecl->propimpl_end();
6500 Prop != PropEnd; ++Prop) {
6501 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6502 continue;
6503 if (!(*Prop)->getPropertyIvarDecl())
6504 continue;
6505 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6506 if (!PD)
6507 continue;
6508 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6509 if (!Getter->isDefined())
6510 InstanceMethods.push_back(Getter);
6511 if (PD->isReadOnly())
6512 continue;
6513 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6514 if (!Setter->isDefined())
6515 InstanceMethods.push_back(Setter);
6516 }
6517
6518 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6519 "_OBJC_$_INSTANCE_METHODS_",
6520 IDecl->getNameAsString(), true);
6521
6522 SmallVector<ObjCMethodDecl *, 32>
6523 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6524
6525 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6526 "_OBJC_$_CLASS_METHODS_",
6527 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006528
6529 // Protocols referenced in class declaration?
6530 // Protocol's super protocol list
6531 std::vector<ObjCProtocolDecl *> RefedProtocols;
6532 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6533 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6534 E = Protocols.end();
6535 I != E; ++I) {
6536 RefedProtocols.push_back(*I);
6537 // Must write out all protocol definitions in current qualifier list,
6538 // and in their nested qualifiers before writing out current definition.
6539 RewriteObjCProtocolMetaData(*I, Result);
6540 }
6541
6542 Write_protocol_list_initializer(Context, Result,
6543 RefedProtocols,
6544 "_OBJC_CLASS_PROTOCOLS_$_",
6545 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006546
6547 // Protocol's property metadata.
6548 std::vector<ObjCPropertyDecl *> ClassProperties;
6549 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6550 E = CDecl->prop_end(); I != E; ++I)
6551 ClassProperties.push_back(*I);
6552
6553 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006554 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006555 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006556 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006557
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006558
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006559 // Data for initializing _class_ro_t metaclass meta-data
6560 uint32_t flags = CLS_META;
6561 std::string InstanceSize;
6562 std::string InstanceStart;
6563
6564
6565 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6566 if (classIsHidden)
6567 flags |= OBJC2_CLS_HIDDEN;
6568
6569 if (!CDecl->getSuperClass())
6570 // class is root
6571 flags |= CLS_ROOT;
6572 InstanceSize = "sizeof(struct _class_t)";
6573 InstanceStart = InstanceSize;
6574 Write__class_ro_t_initializer(Context, Result, flags,
6575 InstanceStart, InstanceSize,
6576 ClassMethods,
6577 0,
6578 0,
6579 0,
6580 "_OBJC_METACLASS_RO_$_",
6581 CDecl->getNameAsString());
6582
6583
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006584 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006585 flags = CLS;
6586 if (classIsHidden)
6587 flags |= OBJC2_CLS_HIDDEN;
6588
6589 if (hasObjCExceptionAttribute(*Context, CDecl))
6590 flags |= CLS_EXCEPTION;
6591
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006592 if (!CDecl->getSuperClass())
6593 // class is root
6594 flags |= CLS_ROOT;
6595
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006596 InstanceSize.clear();
6597 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006598 if (!ObjCSynthesizedStructs.count(CDecl)) {
6599 InstanceSize = "0";
6600 InstanceStart = "0";
6601 }
6602 else {
6603 InstanceSize = "sizeof(struct ";
6604 InstanceSize += CDecl->getNameAsString();
6605 InstanceSize += "_IMPL)";
6606
6607 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6608 if (IVD) {
6609 InstanceStart += "__OFFSETOFIVAR__(struct ";
6610 InstanceStart += CDecl->getNameAsString();
6611 InstanceStart += "_IMPL, ";
6612 InstanceStart += IVD->getNameAsString();
6613 InstanceStart += ")";
6614 }
6615 else
6616 InstanceStart = InstanceSize;
6617 }
6618 Write__class_ro_t_initializer(Context, Result, flags,
6619 InstanceStart, InstanceSize,
6620 InstanceMethods,
6621 RefedProtocols,
6622 IVars,
6623 ClassProperties,
6624 "_OBJC_CLASS_RO_$_",
6625 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006626
6627 Write_class_t(Context, Result,
6628 "OBJC_METACLASS_$_",
6629 CDecl, /*metaclass*/true);
6630
6631 Write_class_t(Context, Result,
6632 "OBJC_CLASS_$_",
6633 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006634
6635 if (ImplementationIsNonLazy(IDecl))
6636 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006637
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006638}
6639
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006640void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6641 int ClsDefCount = ClassImplementation.size();
6642 if (!ClsDefCount)
6643 return;
6644 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6645 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6646 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6647 for (int i = 0; i < ClsDefCount; i++) {
6648 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6649 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6650 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6651 Result += CDecl->getName(); Result += ",\n";
6652 }
6653 Result += "};\n";
6654}
6655
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006656void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6657 int ClsDefCount = ClassImplementation.size();
6658 int CatDefCount = CategoryImplementation.size();
6659
6660 // For each implemented class, write out all its meta data.
6661 for (int i = 0; i < ClsDefCount; i++)
6662 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6663
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006664 RewriteClassSetupInitHook(Result);
6665
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006666 // For each implemented category, write out all its meta data.
6667 for (int i = 0; i < CatDefCount; i++)
6668 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6669
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006670 RewriteCategorySetupInitHook(Result);
6671
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006672 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006673 if (LangOpts.MicrosoftExt)
6674 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006675 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6676 Result += llvm::utostr(ClsDefCount); Result += "]";
6677 Result +=
6678 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6679 "regular,no_dead_strip\")))= {\n";
6680 for (int i = 0; i < ClsDefCount; i++) {
6681 Result += "\t&OBJC_CLASS_$_";
6682 Result += ClassImplementation[i]->getNameAsString();
6683 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006684 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006685 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006686
6687 if (!DefinedNonLazyClasses.empty()) {
6688 if (LangOpts.MicrosoftExt)
6689 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6690 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6691 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6692 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6693 Result += ",\n";
6694 }
6695 Result += "};\n";
6696 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006697 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006698
6699 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006700 if (LangOpts.MicrosoftExt)
6701 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006702 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6703 Result += llvm::utostr(CatDefCount); Result += "]";
6704 Result +=
6705 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6706 "regular,no_dead_strip\")))= {\n";
6707 for (int i = 0; i < CatDefCount; i++) {
6708 Result += "\t&_OBJC_$_CATEGORY_";
6709 Result +=
6710 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6711 Result += "_$_";
6712 Result += CategoryImplementation[i]->getNameAsString();
6713 Result += ",\n";
6714 }
6715 Result += "};\n";
6716 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006717
6718 if (!DefinedNonLazyCategories.empty()) {
6719 if (LangOpts.MicrosoftExt)
6720 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6721 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6722 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6723 Result += "\t&_OBJC_$_CATEGORY_";
6724 Result +=
6725 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6726 Result += "_$_";
6727 Result += DefinedNonLazyCategories[i]->getNameAsString();
6728 Result += ",\n";
6729 }
6730 Result += "};\n";
6731 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006732}
6733
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006734void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6735 if (LangOpts.MicrosoftExt)
6736 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6737
6738 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6739 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006740 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006741}
6742
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006743/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6744/// implementation.
6745void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6746 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006747 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006748 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6749 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006750 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006751 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6752 CDecl = CDecl->getNextClassCategory())
6753 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6754 break;
6755
6756 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006757 FullCategoryName += "_$_";
6758 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006759
6760 // Build _objc_method_list for class's instance methods if needed
6761 SmallVector<ObjCMethodDecl *, 32>
6762 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6763
6764 // If any of our property implementations have associated getters or
6765 // setters, produce metadata for them as well.
6766 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6767 PropEnd = IDecl->propimpl_end();
6768 Prop != PropEnd; ++Prop) {
6769 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6770 continue;
6771 if (!(*Prop)->getPropertyIvarDecl())
6772 continue;
6773 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6774 if (!PD)
6775 continue;
6776 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6777 InstanceMethods.push_back(Getter);
6778 if (PD->isReadOnly())
6779 continue;
6780 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6781 InstanceMethods.push_back(Setter);
6782 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006783
Fariborz Jahanian61186122012-02-17 18:40:41 +00006784 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6785 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6786 FullCategoryName, true);
6787
6788 SmallVector<ObjCMethodDecl *, 32>
6789 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6790
6791 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6792 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6793 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006794
6795 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006796 // Protocol's super protocol list
6797 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006798 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6799 E = CDecl->protocol_end();
6800
6801 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006802 RefedProtocols.push_back(*I);
6803 // Must write out all protocol definitions in current qualifier list,
6804 // and in their nested qualifiers before writing out current definition.
6805 RewriteObjCProtocolMetaData(*I, Result);
6806 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006807
Fariborz Jahanian61186122012-02-17 18:40:41 +00006808 Write_protocol_list_initializer(Context, Result,
6809 RefedProtocols,
6810 "_OBJC_CATEGORY_PROTOCOLS_$_",
6811 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006812
Fariborz Jahanian61186122012-02-17 18:40:41 +00006813 // Protocol's property metadata.
6814 std::vector<ObjCPropertyDecl *> ClassProperties;
6815 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6816 E = CDecl->prop_end(); I != E; ++I)
6817 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006818
Fariborz Jahanian61186122012-02-17 18:40:41 +00006819 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6820 /* Container */0,
6821 "_OBJC_$_PROP_LIST_",
6822 FullCategoryName);
6823
6824 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006825 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006826 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006827 InstanceMethods,
6828 ClassMethods,
6829 RefedProtocols,
6830 ClassProperties);
6831
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006832 // Determine if this category is also "non-lazy".
6833 if (ImplementationIsNonLazy(IDecl))
6834 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006835
6836}
6837
6838void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
6839 int CatDefCount = CategoryImplementation.size();
6840 if (!CatDefCount)
6841 return;
6842 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6843 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6844 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
6845 for (int i = 0; i < CatDefCount; i++) {
6846 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
6847 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
6848 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6849 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
6850 Result += ClassDecl->getName();
6851 Result += "_$_";
6852 Result += CatDecl->getName();
6853 Result += ",\n";
6854 }
6855 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006856}
6857
6858// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6859/// class methods.
6860template<typename MethodIterator>
6861void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6862 MethodIterator MethodEnd,
6863 bool IsInstanceMethod,
6864 StringRef prefix,
6865 StringRef ClassName,
6866 std::string &Result) {
6867 if (MethodBegin == MethodEnd) return;
6868
6869 if (!objc_impl_method) {
6870 /* struct _objc_method {
6871 SEL _cmd;
6872 char *method_types;
6873 void *_imp;
6874 }
6875 */
6876 Result += "\nstruct _objc_method {\n";
6877 Result += "\tSEL _cmd;\n";
6878 Result += "\tchar *method_types;\n";
6879 Result += "\tvoid *_imp;\n";
6880 Result += "};\n";
6881
6882 objc_impl_method = true;
6883 }
6884
6885 // Build _objc_method_list for class's methods if needed
6886
6887 /* struct {
6888 struct _objc_method_list *next_method;
6889 int method_count;
6890 struct _objc_method method_list[];
6891 }
6892 */
6893 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006894 Result += "\n";
6895 if (LangOpts.MicrosoftExt) {
6896 if (IsInstanceMethod)
6897 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6898 else
6899 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6900 }
6901 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006902 Result += "\tstruct _objc_method_list *next_method;\n";
6903 Result += "\tint method_count;\n";
6904 Result += "\tstruct _objc_method method_list[";
6905 Result += utostr(NumMethods);
6906 Result += "];\n} _OBJC_";
6907 Result += prefix;
6908 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6909 Result += "_METHODS_";
6910 Result += ClassName;
6911 Result += " __attribute__ ((used, section (\"__OBJC, __";
6912 Result += IsInstanceMethod ? "inst" : "cls";
6913 Result += "_meth\")))= ";
6914 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6915
6916 Result += "\t,{{(SEL)\"";
6917 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6918 std::string MethodTypeString;
6919 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6920 Result += "\", \"";
6921 Result += MethodTypeString;
6922 Result += "\", (void *)";
6923 Result += MethodInternalNames[*MethodBegin];
6924 Result += "}\n";
6925 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6926 Result += "\t ,{(SEL)\"";
6927 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6928 std::string MethodTypeString;
6929 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6930 Result += "\", \"";
6931 Result += MethodTypeString;
6932 Result += "\", (void *)";
6933 Result += MethodInternalNames[*MethodBegin];
6934 Result += "}\n";
6935 }
6936 Result += "\t }\n};\n";
6937}
6938
6939Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6940 SourceRange OldRange = IV->getSourceRange();
6941 Expr *BaseExpr = IV->getBase();
6942
6943 // Rewrite the base, but without actually doing replaces.
6944 {
6945 DisableReplaceStmtScope S(*this);
6946 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6947 IV->setBase(BaseExpr);
6948 }
6949
6950 ObjCIvarDecl *D = IV->getDecl();
6951
6952 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006953
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006954 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6955 const ObjCInterfaceType *iFaceDecl =
6956 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6957 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6958 // lookup which class implements the instance variable.
6959 ObjCInterfaceDecl *clsDeclared = 0;
6960 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6961 clsDeclared);
6962 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6963
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006964 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006965 std::string IvarOffsetName;
6966 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
6967
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006968 ReferencedIvars[clsDeclared].insert(D);
6969
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006970 // cast offset to "char *".
6971 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6972 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006973 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006974 BaseExpr);
6975 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6976 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6977 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006978 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6979 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006980 SourceLocation());
6981 BinaryOperator *addExpr =
6982 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6983 Context->getPointerType(Context->CharTy),
6984 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006985 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006986 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6987 SourceLocation(),
6988 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006989 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006990 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006991 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006992
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006993 castExpr = NoTypeInfoCStyleCastExpr(Context,
6994 castT,
6995 CK_BitCast,
6996 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006997 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006998 VK_LValue, OK_Ordinary,
6999 SourceLocation());
7000 PE = new (Context) ParenExpr(OldRange.getBegin(),
7001 OldRange.getEnd(),
7002 Exp);
7003
7004 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007005 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007006
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007007 ReplaceStmtWithRange(IV, Replacement, OldRange);
7008 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007009}