blob: 162f7a52894b031642ee1a3ed9c3bad36c3c21c1 [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 Jahaniane35abe12012-04-06 22:29:36 +0000323 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000324 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000325 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
326 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
327 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
328 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
329 SourceLocation OrigEnd);
330 Stmt *RewriteBreakStmt(BreakStmt *S);
331 Stmt *RewriteContinueStmt(ContinueStmt *S);
332 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000333 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000334 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000335
336 // Block rewriting.
337 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
338
339 // Block specific rewrite rules.
340 void RewriteBlockPointerDecl(NamedDecl *VD);
341 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000342 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000343 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
344 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
345
346 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
347 std::string &Result);
348
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000349 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
350
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000351 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
352
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000353 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
354 std::string &Result);
355
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000356 virtual void Initialize(ASTContext &context);
357
358 // Misc. AST transformation routines. Somtimes they end up calling
359 // rewriting routines on the new ASTs.
360 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
361 Expr **args, unsigned nargs,
362 SourceLocation StartLoc=SourceLocation(),
363 SourceLocation EndLoc=SourceLocation());
364
365 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
366 SourceLocation StartLoc=SourceLocation(),
367 SourceLocation EndLoc=SourceLocation());
368
369 void SynthCountByEnumWithState(std::string &buf);
370 void SynthMsgSendFunctionDecl();
371 void SynthMsgSendSuperFunctionDecl();
372 void SynthMsgSendStretFunctionDecl();
373 void SynthMsgSendFpretFunctionDecl();
374 void SynthMsgSendSuperStretFunctionDecl();
375 void SynthGetClassFunctionDecl();
376 void SynthGetMetaClassFunctionDecl();
377 void SynthGetSuperClassFunctionDecl();
378 void SynthSelGetUidFunctionDecl();
379 void SynthSuperContructorFunctionDecl();
380
381 // Rewriting metadata
382 template<typename MethodIterator>
383 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
384 MethodIterator MethodEnd,
385 bool IsInstanceMethod,
386 StringRef prefix,
387 StringRef ClassName,
388 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000389 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
390 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000391 virtual void RewriteObjCProtocolListMetaData(
392 const ObjCList<ObjCProtocolDecl> &Prots,
393 StringRef prefix, StringRef ClassName, std::string &Result);
394 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
395 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000396 virtual void RewriteClassSetupInitHook(std::string &Result);
397
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000398 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000399 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000400 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
401 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000402 virtual void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000403
404 // Rewriting ivar
405 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
406 std::string &Result);
407 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
408
409
410 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
411 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
412 StringRef funcName, std::string Tag);
413 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
414 StringRef funcName, std::string Tag);
415 std::string SynthesizeBlockImpl(BlockExpr *CE,
416 std::string Tag, std::string Desc);
417 std::string SynthesizeBlockDescriptor(std::string DescTag,
418 std::string ImplTag,
419 int i, StringRef funcName,
420 unsigned hasCopy);
421 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
422 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
423 StringRef FunName);
424 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
425 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000426 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000427
428 // Misc. helper routines.
429 QualType getProtocolType();
430 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000431 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
432 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
433 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
434
435 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
436 void CollectBlockDeclRefInfo(BlockExpr *Exp);
437 void GetBlockDeclRefExprs(Stmt *S);
438 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000439 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000440 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
441
442 // We avoid calling Type::isBlockPointerType(), since it operates on the
443 // canonical type. We only care if the top-level type is a closure pointer.
444 bool isTopLevelBlockPointerType(QualType T) {
445 return isa<BlockPointerType>(T);
446 }
447
448 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
449 /// to a function pointer type and upon success, returns true; false
450 /// otherwise.
451 bool convertBlockPointerToFunctionPointer(QualType &T) {
452 if (isTopLevelBlockPointerType(T)) {
453 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
454 T = Context->getPointerType(BPT->getPointeeType());
455 return true;
456 }
457 return false;
458 }
459
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000460 bool convertObjCTypeToCStyleType(QualType &T);
461
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000462 bool needToScanForQualifiers(QualType T);
463 QualType getSuperStructType();
464 QualType getConstantStringStructType();
465 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
466 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
467
468 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000469 if (T->isObjCQualifiedIdType()) {
470 bool isConst = T.isConstQualified();
471 T = isConst ? Context->getObjCIdType().withConst()
472 : Context->getObjCIdType();
473 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000474 else if (T->isObjCQualifiedClassType())
475 T = Context->getObjCClassType();
476 else if (T->isObjCObjectPointerType() &&
477 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
478 if (const ObjCObjectPointerType * OBJPT =
479 T->getAsObjCInterfacePointerType()) {
480 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
481 T = QualType(IFaceT, 0);
482 T = Context->getPointerType(T);
483 }
484 }
485 }
486
487 // FIXME: This predicate seems like it would be useful to add to ASTContext.
488 bool isObjCType(QualType T) {
489 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
490 return false;
491
492 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
493
494 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
495 OCT == Context->getCanonicalType(Context->getObjCClassType()))
496 return true;
497
498 if (const PointerType *PT = OCT->getAs<PointerType>()) {
499 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
500 PT->getPointeeType()->isObjCQualifiedIdType())
501 return true;
502 }
503 return false;
504 }
505 bool PointerTypeTakesAnyBlockArguments(QualType QT);
506 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
507 void GetExtentOfArgList(const char *Name, const char *&LParen,
508 const char *&RParen);
509
510 void QuoteDoublequotes(std::string &From, std::string &To) {
511 for (unsigned i = 0; i < From.length(); i++) {
512 if (From[i] == '"')
513 To += "\\\"";
514 else
515 To += From[i];
516 }
517 }
518
519 QualType getSimpleFunctionType(QualType result,
520 const QualType *args,
521 unsigned numArgs,
522 bool variadic = false) {
523 if (result == Context->getObjCInstanceType())
524 result = Context->getObjCIdType();
525 FunctionProtoType::ExtProtoInfo fpi;
526 fpi.Variadic = variadic;
527 return Context->getFunctionType(result, args, numArgs, fpi);
528 }
529
530 // Helper function: create a CStyleCastExpr with trivial type source info.
531 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
532 CastKind Kind, Expr *E) {
533 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
534 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
535 SourceLocation(), SourceLocation());
536 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000537
538 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
539 IdentifierInfo* II = &Context->Idents.get("load");
540 Selector LoadSel = Context->Selectors.getSelector(0, &II);
541 return OD->getClassMethod(LoadSel) != 0;
542 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000543 };
544
545}
546
547void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
548 NamedDecl *D) {
549 if (const FunctionProtoType *fproto
550 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
551 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
552 E = fproto->arg_type_end(); I && (I != E); ++I)
553 if (isTopLevelBlockPointerType(*I)) {
554 // All the args are checked/rewritten. Don't call twice!
555 RewriteBlockPointerDecl(D);
556 break;
557 }
558 }
559}
560
561void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
562 const PointerType *PT = funcType->getAs<PointerType>();
563 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
564 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
565}
566
567static bool IsHeaderFile(const std::string &Filename) {
568 std::string::size_type DotPos = Filename.rfind('.');
569
570 if (DotPos == std::string::npos) {
571 // no file extension
572 return false;
573 }
574
575 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
576 // C header: .h
577 // C++ header: .hh or .H;
578 return Ext == "h" || Ext == "hh" || Ext == "H";
579}
580
581RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
582 DiagnosticsEngine &D, const LangOptions &LOpts,
583 bool silenceMacroWarn)
584 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
585 SilenceRewriteMacroWarning(silenceMacroWarn) {
586 IsHeader = IsHeaderFile(inFile);
587 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
588 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000589 // FIXME. This should be an error. But if block is not called, it is OK. And it
590 // may break including some headers.
591 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
592 "rewriting block literal declared in global scope is not implemented");
593
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000594 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
595 DiagnosticsEngine::Warning,
596 "rewriter doesn't support user-specified control flow semantics "
597 "for @try/@finally (code may not execute properly)");
598}
599
600ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
601 raw_ostream* OS,
602 DiagnosticsEngine &Diags,
603 const LangOptions &LOpts,
604 bool SilenceRewriteMacroWarning) {
605 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
606}
607
608void RewriteModernObjC::InitializeCommon(ASTContext &context) {
609 Context = &context;
610 SM = &Context->getSourceManager();
611 TUDecl = Context->getTranslationUnitDecl();
612 MsgSendFunctionDecl = 0;
613 MsgSendSuperFunctionDecl = 0;
614 MsgSendStretFunctionDecl = 0;
615 MsgSendSuperStretFunctionDecl = 0;
616 MsgSendFpretFunctionDecl = 0;
617 GetClassFunctionDecl = 0;
618 GetMetaClassFunctionDecl = 0;
619 GetSuperClassFunctionDecl = 0;
620 SelGetUidFunctionDecl = 0;
621 CFStringFunctionDecl = 0;
622 ConstantStringClassReference = 0;
623 NSStringRecord = 0;
624 CurMethodDef = 0;
625 CurFunctionDef = 0;
626 CurFunctionDeclToDeclareForBlock = 0;
627 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000628 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000629 SuperStructDecl = 0;
630 ProtocolTypeDecl = 0;
631 ConstantStringDecl = 0;
632 BcLabelCount = 0;
633 SuperContructorFunctionDecl = 0;
634 NumObjCStringLiterals = 0;
635 PropParentMap = 0;
636 CurrentBody = 0;
637 DisableReplaceStmt = false;
638 objc_impl_method = false;
639
640 // Get the ID and start/end of the main file.
641 MainFileID = SM->getMainFileID();
642 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
643 MainFileStart = MainBuf->getBufferStart();
644 MainFileEnd = MainBuf->getBufferEnd();
645
David Blaikie4e4d0842012-03-11 07:00:24 +0000646 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000647}
648
649//===----------------------------------------------------------------------===//
650// Top Level Driver Code
651//===----------------------------------------------------------------------===//
652
653void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
654 if (Diags.hasErrorOccurred())
655 return;
656
657 // Two cases: either the decl could be in the main file, or it could be in a
658 // #included file. If the former, rewrite it now. If the later, check to see
659 // if we rewrote the #include/#import.
660 SourceLocation Loc = D->getLocation();
661 Loc = SM->getExpansionLoc(Loc);
662
663 // If this is for a builtin, ignore it.
664 if (Loc.isInvalid()) return;
665
666 // Look for built-in declarations that we need to refer during the rewrite.
667 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
668 RewriteFunctionDecl(FD);
669 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
670 // declared in <Foundation/NSString.h>
671 if (FVD->getName() == "_NSConstantStringClassReference") {
672 ConstantStringClassReference = FVD;
673 return;
674 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000675 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
676 RewriteCategoryDecl(CD);
677 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
678 if (PD->isThisDeclarationADefinition())
679 RewriteProtocolDecl(PD);
680 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000681 // FIXME. This will not work in all situations and leaving it out
682 // is harmless.
683 // RewriteLinkageSpec(LSD);
684
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000685 // Recurse into linkage specifications
686 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
687 DIEnd = LSD->decls_end();
688 DI != DIEnd; ) {
689 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
690 if (!IFace->isThisDeclarationADefinition()) {
691 SmallVector<Decl *, 8> DG;
692 SourceLocation StartLoc = IFace->getLocStart();
693 do {
694 if (isa<ObjCInterfaceDecl>(*DI) &&
695 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
696 StartLoc == (*DI)->getLocStart())
697 DG.push_back(*DI);
698 else
699 break;
700
701 ++DI;
702 } while (DI != DIEnd);
703 RewriteForwardClassDecl(DG);
704 continue;
705 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000706 else {
707 // Keep track of all interface declarations seen.
708 ObjCInterfacesSeen.push_back(IFace);
709 ++DI;
710 continue;
711 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000712 }
713
714 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
715 if (!Proto->isThisDeclarationADefinition()) {
716 SmallVector<Decl *, 8> DG;
717 SourceLocation StartLoc = Proto->getLocStart();
718 do {
719 if (isa<ObjCProtocolDecl>(*DI) &&
720 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
721 StartLoc == (*DI)->getLocStart())
722 DG.push_back(*DI);
723 else
724 break;
725
726 ++DI;
727 } while (DI != DIEnd);
728 RewriteForwardProtocolDecl(DG);
729 continue;
730 }
731 }
732
733 HandleTopLevelSingleDecl(*DI);
734 ++DI;
735 }
736 }
737 // If we have a decl in the main file, see if we should rewrite it.
738 if (SM->isFromMainFile(Loc))
739 return HandleDeclInMainFile(D);
740}
741
742//===----------------------------------------------------------------------===//
743// Syntactic (non-AST) Rewriting Code
744//===----------------------------------------------------------------------===//
745
746void RewriteModernObjC::RewriteInclude() {
747 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
748 StringRef MainBuf = SM->getBufferData(MainFileID);
749 const char *MainBufStart = MainBuf.begin();
750 const char *MainBufEnd = MainBuf.end();
751 size_t ImportLen = strlen("import");
752
753 // Loop over the whole file, looking for includes.
754 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
755 if (*BufPtr == '#') {
756 if (++BufPtr == MainBufEnd)
757 return;
758 while (*BufPtr == ' ' || *BufPtr == '\t')
759 if (++BufPtr == MainBufEnd)
760 return;
761 if (!strncmp(BufPtr, "import", ImportLen)) {
762 // replace import with include
763 SourceLocation ImportLoc =
764 LocStart.getLocWithOffset(BufPtr-MainBufStart);
765 ReplaceText(ImportLoc, ImportLen, "include");
766 BufPtr += ImportLen;
767 }
768 }
769 }
770}
771
772static std::string getIvarAccessString(ObjCIvarDecl *OID) {
773 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
774 std::string S;
775 S = "((struct ";
776 S += ClassDecl->getIdentifier()->getName();
777 S += "_IMPL *)self)->";
778 S += OID->getName();
779 return S;
780}
781
782void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
783 ObjCImplementationDecl *IMD,
784 ObjCCategoryImplDecl *CID) {
785 static bool objcGetPropertyDefined = false;
786 static bool objcSetPropertyDefined = false;
787 SourceLocation startLoc = PID->getLocStart();
788 InsertText(startLoc, "// ");
789 const char *startBuf = SM->getCharacterData(startLoc);
790 assert((*startBuf == '@') && "bogus @synthesize location");
791 const char *semiBuf = strchr(startBuf, ';');
792 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
793 SourceLocation onePastSemiLoc =
794 startLoc.getLocWithOffset(semiBuf-startBuf+1);
795
796 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
797 return; // FIXME: is this correct?
798
799 // Generate the 'getter' function.
800 ObjCPropertyDecl *PD = PID->getPropertyDecl();
801 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
802
803 if (!OID)
804 return;
805 unsigned Attributes = PD->getPropertyAttributes();
806 if (!PD->getGetterMethodDecl()->isDefined()) {
807 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
808 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
809 ObjCPropertyDecl::OBJC_PR_copy));
810 std::string Getr;
811 if (GenGetProperty && !objcGetPropertyDefined) {
812 objcGetPropertyDefined = true;
813 // FIXME. Is this attribute correct in all cases?
814 Getr = "\nextern \"C\" __declspec(dllimport) "
815 "id objc_getProperty(id, SEL, long, bool);\n";
816 }
817 RewriteObjCMethodDecl(OID->getContainingInterface(),
818 PD->getGetterMethodDecl(), Getr);
819 Getr += "{ ";
820 // Synthesize an explicit cast to gain access to the ivar.
821 // See objc-act.c:objc_synthesize_new_getter() for details.
822 if (GenGetProperty) {
823 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
824 Getr += "typedef ";
825 const FunctionType *FPRetType = 0;
826 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
827 FPRetType);
828 Getr += " _TYPE";
829 if (FPRetType) {
830 Getr += ")"; // close the precedence "scope" for "*".
831
832 // Now, emit the argument types (if any).
833 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
834 Getr += "(";
835 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
836 if (i) Getr += ", ";
837 std::string ParamStr = FT->getArgType(i).getAsString(
838 Context->getPrintingPolicy());
839 Getr += ParamStr;
840 }
841 if (FT->isVariadic()) {
842 if (FT->getNumArgs()) Getr += ", ";
843 Getr += "...";
844 }
845 Getr += ")";
846 } else
847 Getr += "()";
848 }
849 Getr += ";\n";
850 Getr += "return (_TYPE)";
851 Getr += "objc_getProperty(self, _cmd, ";
852 RewriteIvarOffsetComputation(OID, Getr);
853 Getr += ", 1)";
854 }
855 else
856 Getr += "return " + getIvarAccessString(OID);
857 Getr += "; }";
858 InsertText(onePastSemiLoc, Getr);
859 }
860
861 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
862 return;
863
864 // Generate the 'setter' function.
865 std::string Setr;
866 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
867 ObjCPropertyDecl::OBJC_PR_copy);
868 if (GenSetProperty && !objcSetPropertyDefined) {
869 objcSetPropertyDefined = true;
870 // FIXME. Is this attribute correct in all cases?
871 Setr = "\nextern \"C\" __declspec(dllimport) "
872 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
873 }
874
875 RewriteObjCMethodDecl(OID->getContainingInterface(),
876 PD->getSetterMethodDecl(), Setr);
877 Setr += "{ ";
878 // Synthesize an explicit cast to initialize the ivar.
879 // See objc-act.c:objc_synthesize_new_setter() for details.
880 if (GenSetProperty) {
881 Setr += "objc_setProperty (self, _cmd, ";
882 RewriteIvarOffsetComputation(OID, Setr);
883 Setr += ", (id)";
884 Setr += PD->getName();
885 Setr += ", ";
886 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
887 Setr += "0, ";
888 else
889 Setr += "1, ";
890 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
891 Setr += "1)";
892 else
893 Setr += "0)";
894 }
895 else {
896 Setr += getIvarAccessString(OID) + " = ";
897 Setr += PD->getName();
898 }
899 Setr += "; }";
900 InsertText(onePastSemiLoc, Setr);
901}
902
903static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
904 std::string &typedefString) {
905 typedefString += "#ifndef _REWRITER_typedef_";
906 typedefString += ForwardDecl->getNameAsString();
907 typedefString += "\n";
908 typedefString += "#define _REWRITER_typedef_";
909 typedefString += ForwardDecl->getNameAsString();
910 typedefString += "\n";
911 typedefString += "typedef struct objc_object ";
912 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000913 // typedef struct { } _objc_exc_Classname;
914 typedefString += ";\ntypedef struct {} _objc_exc_";
915 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000916 typedefString += ";\n#endif\n";
917}
918
919void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
920 const std::string &typedefString) {
921 SourceLocation startLoc = ClassDecl->getLocStart();
922 const char *startBuf = SM->getCharacterData(startLoc);
923 const char *semiPtr = strchr(startBuf, ';');
924 // Replace the @class with typedefs corresponding to the classes.
925 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
926}
927
928void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
929 std::string typedefString;
930 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
931 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
932 if (I == D.begin()) {
933 // Translate to typedef's that forward reference structs with the same name
934 // as the class. As a convenience, we include the original declaration
935 // as a comment.
936 typedefString += "// @class ";
937 typedefString += ForwardDecl->getNameAsString();
938 typedefString += ";\n";
939 }
940 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
941 }
942 DeclGroupRef::iterator I = D.begin();
943 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
944}
945
946void RewriteModernObjC::RewriteForwardClassDecl(
947 const llvm::SmallVector<Decl*, 8> &D) {
948 std::string typedefString;
949 for (unsigned i = 0; i < D.size(); i++) {
950 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
951 if (i == 0) {
952 typedefString += "// @class ";
953 typedefString += ForwardDecl->getNameAsString();
954 typedefString += ";\n";
955 }
956 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
957 }
958 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
959}
960
961void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
962 // When method is a synthesized one, such as a getter/setter there is
963 // nothing to rewrite.
964 if (Method->isImplicit())
965 return;
966 SourceLocation LocStart = Method->getLocStart();
967 SourceLocation LocEnd = Method->getLocEnd();
968
969 if (SM->getExpansionLineNumber(LocEnd) >
970 SM->getExpansionLineNumber(LocStart)) {
971 InsertText(LocStart, "#if 0\n");
972 ReplaceText(LocEnd, 1, ";\n#endif\n");
973 } else {
974 InsertText(LocStart, "// ");
975 }
976}
977
978void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
979 SourceLocation Loc = prop->getAtLoc();
980
981 ReplaceText(Loc, 0, "// ");
982 // FIXME: handle properties that are declared across multiple lines.
983}
984
985void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
986 SourceLocation LocStart = CatDecl->getLocStart();
987
988 // FIXME: handle category headers that are declared across multiple lines.
989 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000990 if (CatDecl->getIvarLBraceLoc().isValid())
991 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000992 for (ObjCCategoryDecl::ivar_iterator
993 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
994 ObjCIvarDecl *Ivar = (*I);
995 SourceLocation LocStart = Ivar->getLocStart();
996 ReplaceText(LocStart, 0, "// ");
997 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000998 if (CatDecl->getIvarRBraceLoc().isValid())
999 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
1000
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001001 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1002 E = CatDecl->prop_end(); I != E; ++I)
1003 RewriteProperty(*I);
1004
1005 for (ObjCCategoryDecl::instmeth_iterator
1006 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1007 I != E; ++I)
1008 RewriteMethodDeclaration(*I);
1009 for (ObjCCategoryDecl::classmeth_iterator
1010 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1011 I != E; ++I)
1012 RewriteMethodDeclaration(*I);
1013
1014 // Lastly, comment out the @end.
1015 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1016 strlen("@end"), "/* @end */");
1017}
1018
1019void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1020 SourceLocation LocStart = PDecl->getLocStart();
1021 assert(PDecl->isThisDeclarationADefinition());
1022
1023 // FIXME: handle protocol headers that are declared across multiple lines.
1024 ReplaceText(LocStart, 0, "// ");
1025
1026 for (ObjCProtocolDecl::instmeth_iterator
1027 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1028 I != E; ++I)
1029 RewriteMethodDeclaration(*I);
1030 for (ObjCProtocolDecl::classmeth_iterator
1031 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1032 I != E; ++I)
1033 RewriteMethodDeclaration(*I);
1034
1035 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1036 E = PDecl->prop_end(); I != E; ++I)
1037 RewriteProperty(*I);
1038
1039 // Lastly, comment out the @end.
1040 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1041 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1042
1043 // Must comment out @optional/@required
1044 const char *startBuf = SM->getCharacterData(LocStart);
1045 const char *endBuf = SM->getCharacterData(LocEnd);
1046 for (const char *p = startBuf; p < endBuf; p++) {
1047 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1048 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1049 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1050
1051 }
1052 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1053 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1054 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1055
1056 }
1057 }
1058}
1059
1060void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1061 SourceLocation LocStart = (*D.begin())->getLocStart();
1062 if (LocStart.isInvalid())
1063 llvm_unreachable("Invalid SourceLocation");
1064 // FIXME: handle forward protocol that are declared across multiple lines.
1065 ReplaceText(LocStart, 0, "// ");
1066}
1067
1068void
1069RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1070 SourceLocation LocStart = DG[0]->getLocStart();
1071 if (LocStart.isInvalid())
1072 llvm_unreachable("Invalid SourceLocation");
1073 // FIXME: handle forward protocol that are declared across multiple lines.
1074 ReplaceText(LocStart, 0, "// ");
1075}
1076
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001077void
1078RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1079 SourceLocation LocStart = LSD->getExternLoc();
1080 if (LocStart.isInvalid())
1081 llvm_unreachable("Invalid extern SourceLocation");
1082
1083 ReplaceText(LocStart, 0, "// ");
1084 if (!LSD->hasBraces())
1085 return;
1086 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1087 SourceLocation LocRBrace = LSD->getRBraceLoc();
1088 if (LocRBrace.isInvalid())
1089 llvm_unreachable("Invalid rbrace SourceLocation");
1090 ReplaceText(LocRBrace, 0, "// ");
1091}
1092
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001093void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1094 const FunctionType *&FPRetType) {
1095 if (T->isObjCQualifiedIdType())
1096 ResultStr += "id";
1097 else if (T->isFunctionPointerType() ||
1098 T->isBlockPointerType()) {
1099 // needs special handling, since pointer-to-functions have special
1100 // syntax (where a decaration models use).
1101 QualType retType = T;
1102 QualType PointeeTy;
1103 if (const PointerType* PT = retType->getAs<PointerType>())
1104 PointeeTy = PT->getPointeeType();
1105 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1106 PointeeTy = BPT->getPointeeType();
1107 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1108 ResultStr += FPRetType->getResultType().getAsString(
1109 Context->getPrintingPolicy());
1110 ResultStr += "(*";
1111 }
1112 } else
1113 ResultStr += T.getAsString(Context->getPrintingPolicy());
1114}
1115
1116void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1117 ObjCMethodDecl *OMD,
1118 std::string &ResultStr) {
1119 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1120 const FunctionType *FPRetType = 0;
1121 ResultStr += "\nstatic ";
1122 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1123 ResultStr += " ";
1124
1125 // Unique method name
1126 std::string NameStr;
1127
1128 if (OMD->isInstanceMethod())
1129 NameStr += "_I_";
1130 else
1131 NameStr += "_C_";
1132
1133 NameStr += IDecl->getNameAsString();
1134 NameStr += "_";
1135
1136 if (ObjCCategoryImplDecl *CID =
1137 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1138 NameStr += CID->getNameAsString();
1139 NameStr += "_";
1140 }
1141 // Append selector names, replacing ':' with '_'
1142 {
1143 std::string selString = OMD->getSelector().getAsString();
1144 int len = selString.size();
1145 for (int i = 0; i < len; i++)
1146 if (selString[i] == ':')
1147 selString[i] = '_';
1148 NameStr += selString;
1149 }
1150 // Remember this name for metadata emission
1151 MethodInternalNames[OMD] = NameStr;
1152 ResultStr += NameStr;
1153
1154 // Rewrite arguments
1155 ResultStr += "(";
1156
1157 // invisible arguments
1158 if (OMD->isInstanceMethod()) {
1159 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1160 selfTy = Context->getPointerType(selfTy);
1161 if (!LangOpts.MicrosoftExt) {
1162 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1163 ResultStr += "struct ";
1164 }
1165 // When rewriting for Microsoft, explicitly omit the structure name.
1166 ResultStr += IDecl->getNameAsString();
1167 ResultStr += " *";
1168 }
1169 else
1170 ResultStr += Context->getObjCClassType().getAsString(
1171 Context->getPrintingPolicy());
1172
1173 ResultStr += " self, ";
1174 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1175 ResultStr += " _cmd";
1176
1177 // Method arguments.
1178 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1179 E = OMD->param_end(); PI != E; ++PI) {
1180 ParmVarDecl *PDecl = *PI;
1181 ResultStr += ", ";
1182 if (PDecl->getType()->isObjCQualifiedIdType()) {
1183 ResultStr += "id ";
1184 ResultStr += PDecl->getNameAsString();
1185 } else {
1186 std::string Name = PDecl->getNameAsString();
1187 QualType QT = PDecl->getType();
1188 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001189 (void)convertBlockPointerToFunctionPointer(QT);
1190 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001191 ResultStr += Name;
1192 }
1193 }
1194 if (OMD->isVariadic())
1195 ResultStr += ", ...";
1196 ResultStr += ") ";
1197
1198 if (FPRetType) {
1199 ResultStr += ")"; // close the precedence "scope" for "*".
1200
1201 // Now, emit the argument types (if any).
1202 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1203 ResultStr += "(";
1204 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1205 if (i) ResultStr += ", ";
1206 std::string ParamStr = FT->getArgType(i).getAsString(
1207 Context->getPrintingPolicy());
1208 ResultStr += ParamStr;
1209 }
1210 if (FT->isVariadic()) {
1211 if (FT->getNumArgs()) ResultStr += ", ";
1212 ResultStr += "...";
1213 }
1214 ResultStr += ")";
1215 } else {
1216 ResultStr += "()";
1217 }
1218 }
1219}
1220void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1221 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1222 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1223
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001224 if (IMD) {
1225 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001226 if (IMD->getIvarLBraceLoc().isValid())
1227 InsertText(IMD->getIvarLBraceLoc(), "// ");
1228 for (ObjCImplementationDecl::ivar_iterator
1229 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1230 ObjCIvarDecl *Ivar = (*I);
1231 SourceLocation LocStart = Ivar->getLocStart();
1232 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001233 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001234 if (IMD->getIvarRBraceLoc().isValid())
1235 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001236 }
1237 else
1238 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001239
1240 for (ObjCCategoryImplDecl::instmeth_iterator
1241 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1242 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1243 I != E; ++I) {
1244 std::string ResultStr;
1245 ObjCMethodDecl *OMD = *I;
1246 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1247 SourceLocation LocStart = OMD->getLocStart();
1248 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1249
1250 const char *startBuf = SM->getCharacterData(LocStart);
1251 const char *endBuf = SM->getCharacterData(LocEnd);
1252 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1253 }
1254
1255 for (ObjCCategoryImplDecl::classmeth_iterator
1256 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1257 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1258 I != E; ++I) {
1259 std::string ResultStr;
1260 ObjCMethodDecl *OMD = *I;
1261 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1262 SourceLocation LocStart = OMD->getLocStart();
1263 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1264
1265 const char *startBuf = SM->getCharacterData(LocStart);
1266 const char *endBuf = SM->getCharacterData(LocEnd);
1267 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1268 }
1269 for (ObjCCategoryImplDecl::propimpl_iterator
1270 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1271 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1272 I != E; ++I) {
1273 RewritePropertyImplDecl(*I, IMD, CID);
1274 }
1275
1276 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1277}
1278
1279void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001280 // Do not synthesize more than once.
1281 if (ObjCSynthesizedStructs.count(ClassDecl))
1282 return;
1283 // Make sure super class's are written before current class is written.
1284 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1285 while (SuperClass) {
1286 RewriteInterfaceDecl(SuperClass);
1287 SuperClass = SuperClass->getSuperClass();
1288 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001289 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001290 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001291 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001292 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001293 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1294
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001295 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001296 // Mark this typedef as having been written into its c++ equivalent.
1297 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001298
1299 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001300 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001301 RewriteProperty(*I);
1302 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001303 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001304 I != E; ++I)
1305 RewriteMethodDeclaration(*I);
1306 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001307 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001308 I != E; ++I)
1309 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001310
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001311 // Lastly, comment out the @end.
1312 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1313 "/* @end */");
1314 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001315}
1316
1317Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1318 SourceRange OldRange = PseudoOp->getSourceRange();
1319
1320 // We just magically know some things about the structure of this
1321 // expression.
1322 ObjCMessageExpr *OldMsg =
1323 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1324 PseudoOp->getNumSemanticExprs() - 1));
1325
1326 // Because the rewriter doesn't allow us to rewrite rewritten code,
1327 // we need to suppress rewriting the sub-statements.
1328 Expr *Base, *RHS;
1329 {
1330 DisableReplaceStmtScope S(*this);
1331
1332 // Rebuild the base expression if we have one.
1333 Base = 0;
1334 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1335 Base = OldMsg->getInstanceReceiver();
1336 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1337 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1338 }
1339
1340 // Rebuild the RHS.
1341 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1342 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1343 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1344 }
1345
1346 // TODO: avoid this copy.
1347 SmallVector<SourceLocation, 1> SelLocs;
1348 OldMsg->getSelectorLocs(SelLocs);
1349
1350 ObjCMessageExpr *NewMsg = 0;
1351 switch (OldMsg->getReceiverKind()) {
1352 case ObjCMessageExpr::Class:
1353 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1354 OldMsg->getValueKind(),
1355 OldMsg->getLeftLoc(),
1356 OldMsg->getClassReceiverTypeInfo(),
1357 OldMsg->getSelector(),
1358 SelLocs,
1359 OldMsg->getMethodDecl(),
1360 RHS,
1361 OldMsg->getRightLoc(),
1362 OldMsg->isImplicit());
1363 break;
1364
1365 case ObjCMessageExpr::Instance:
1366 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1367 OldMsg->getValueKind(),
1368 OldMsg->getLeftLoc(),
1369 Base,
1370 OldMsg->getSelector(),
1371 SelLocs,
1372 OldMsg->getMethodDecl(),
1373 RHS,
1374 OldMsg->getRightLoc(),
1375 OldMsg->isImplicit());
1376 break;
1377
1378 case ObjCMessageExpr::SuperClass:
1379 case ObjCMessageExpr::SuperInstance:
1380 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1381 OldMsg->getValueKind(),
1382 OldMsg->getLeftLoc(),
1383 OldMsg->getSuperLoc(),
1384 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1385 OldMsg->getSuperType(),
1386 OldMsg->getSelector(),
1387 SelLocs,
1388 OldMsg->getMethodDecl(),
1389 RHS,
1390 OldMsg->getRightLoc(),
1391 OldMsg->isImplicit());
1392 break;
1393 }
1394
1395 Stmt *Replacement = SynthMessageExpr(NewMsg);
1396 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1397 return Replacement;
1398}
1399
1400Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1401 SourceRange OldRange = PseudoOp->getSourceRange();
1402
1403 // We just magically know some things about the structure of this
1404 // expression.
1405 ObjCMessageExpr *OldMsg =
1406 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1407
1408 // Because the rewriter doesn't allow us to rewrite rewritten code,
1409 // we need to suppress rewriting the sub-statements.
1410 Expr *Base = 0;
1411 {
1412 DisableReplaceStmtScope S(*this);
1413
1414 // Rebuild the base expression if we have one.
1415 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1416 Base = OldMsg->getInstanceReceiver();
1417 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1418 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1419 }
1420 }
1421
1422 // Intentionally empty.
1423 SmallVector<SourceLocation, 1> SelLocs;
1424 SmallVector<Expr*, 1> Args;
1425
1426 ObjCMessageExpr *NewMsg = 0;
1427 switch (OldMsg->getReceiverKind()) {
1428 case ObjCMessageExpr::Class:
1429 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1430 OldMsg->getValueKind(),
1431 OldMsg->getLeftLoc(),
1432 OldMsg->getClassReceiverTypeInfo(),
1433 OldMsg->getSelector(),
1434 SelLocs,
1435 OldMsg->getMethodDecl(),
1436 Args,
1437 OldMsg->getRightLoc(),
1438 OldMsg->isImplicit());
1439 break;
1440
1441 case ObjCMessageExpr::Instance:
1442 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1443 OldMsg->getValueKind(),
1444 OldMsg->getLeftLoc(),
1445 Base,
1446 OldMsg->getSelector(),
1447 SelLocs,
1448 OldMsg->getMethodDecl(),
1449 Args,
1450 OldMsg->getRightLoc(),
1451 OldMsg->isImplicit());
1452 break;
1453
1454 case ObjCMessageExpr::SuperClass:
1455 case ObjCMessageExpr::SuperInstance:
1456 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1457 OldMsg->getValueKind(),
1458 OldMsg->getLeftLoc(),
1459 OldMsg->getSuperLoc(),
1460 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1461 OldMsg->getSuperType(),
1462 OldMsg->getSelector(),
1463 SelLocs,
1464 OldMsg->getMethodDecl(),
1465 Args,
1466 OldMsg->getRightLoc(),
1467 OldMsg->isImplicit());
1468 break;
1469 }
1470
1471 Stmt *Replacement = SynthMessageExpr(NewMsg);
1472 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1473 return Replacement;
1474}
1475
1476/// SynthCountByEnumWithState - To print:
1477/// ((unsigned int (*)
1478/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1479/// (void *)objc_msgSend)((id)l_collection,
1480/// sel_registerName(
1481/// "countByEnumeratingWithState:objects:count:"),
1482/// &enumState,
1483/// (id *)__rw_items, (unsigned int)16)
1484///
1485void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1486 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1487 "id *, unsigned int))(void *)objc_msgSend)";
1488 buf += "\n\t\t";
1489 buf += "((id)l_collection,\n\t\t";
1490 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1491 buf += "\n\t\t";
1492 buf += "&enumState, "
1493 "(id *)__rw_items, (unsigned int)16)";
1494}
1495
1496/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1497/// statement to exit to its outer synthesized loop.
1498///
1499Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1500 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1501 return S;
1502 // replace break with goto __break_label
1503 std::string buf;
1504
1505 SourceLocation startLoc = S->getLocStart();
1506 buf = "goto __break_label_";
1507 buf += utostr(ObjCBcLabelNo.back());
1508 ReplaceText(startLoc, strlen("break"), buf);
1509
1510 return 0;
1511}
1512
1513/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1514/// statement to continue with its inner synthesized loop.
1515///
1516Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1517 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1518 return S;
1519 // replace continue with goto __continue_label
1520 std::string buf;
1521
1522 SourceLocation startLoc = S->getLocStart();
1523 buf = "goto __continue_label_";
1524 buf += utostr(ObjCBcLabelNo.back());
1525 ReplaceText(startLoc, strlen("continue"), buf);
1526
1527 return 0;
1528}
1529
1530/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1531/// It rewrites:
1532/// for ( type elem in collection) { stmts; }
1533
1534/// Into:
1535/// {
1536/// type elem;
1537/// struct __objcFastEnumerationState enumState = { 0 };
1538/// id __rw_items[16];
1539/// id l_collection = (id)collection;
1540/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1541/// objects:__rw_items count:16];
1542/// if (limit) {
1543/// unsigned long startMutations = *enumState.mutationsPtr;
1544/// do {
1545/// unsigned long counter = 0;
1546/// do {
1547/// if (startMutations != *enumState.mutationsPtr)
1548/// objc_enumerationMutation(l_collection);
1549/// elem = (type)enumState.itemsPtr[counter++];
1550/// stmts;
1551/// __continue_label: ;
1552/// } while (counter < limit);
1553/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1554/// objects:__rw_items count:16]);
1555/// elem = nil;
1556/// __break_label: ;
1557/// }
1558/// else
1559/// elem = nil;
1560/// }
1561///
1562Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1563 SourceLocation OrigEnd) {
1564 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1565 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1566 "ObjCForCollectionStmt Statement stack mismatch");
1567 assert(!ObjCBcLabelNo.empty() &&
1568 "ObjCForCollectionStmt - Label No stack empty");
1569
1570 SourceLocation startLoc = S->getLocStart();
1571 const char *startBuf = SM->getCharacterData(startLoc);
1572 StringRef elementName;
1573 std::string elementTypeAsString;
1574 std::string buf;
1575 buf = "\n{\n\t";
1576 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1577 // type elem;
1578 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1579 QualType ElementType = cast<ValueDecl>(D)->getType();
1580 if (ElementType->isObjCQualifiedIdType() ||
1581 ElementType->isObjCQualifiedInterfaceType())
1582 // Simply use 'id' for all qualified types.
1583 elementTypeAsString = "id";
1584 else
1585 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1586 buf += elementTypeAsString;
1587 buf += " ";
1588 elementName = D->getName();
1589 buf += elementName;
1590 buf += ";\n\t";
1591 }
1592 else {
1593 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1594 elementName = DR->getDecl()->getName();
1595 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1596 if (VD->getType()->isObjCQualifiedIdType() ||
1597 VD->getType()->isObjCQualifiedInterfaceType())
1598 // Simply use 'id' for all qualified types.
1599 elementTypeAsString = "id";
1600 else
1601 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1602 }
1603
1604 // struct __objcFastEnumerationState enumState = { 0 };
1605 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1606 // id __rw_items[16];
1607 buf += "id __rw_items[16];\n\t";
1608 // id l_collection = (id)
1609 buf += "id l_collection = (id)";
1610 // Find start location of 'collection' the hard way!
1611 const char *startCollectionBuf = startBuf;
1612 startCollectionBuf += 3; // skip 'for'
1613 startCollectionBuf = strchr(startCollectionBuf, '(');
1614 startCollectionBuf++; // skip '('
1615 // find 'in' and skip it.
1616 while (*startCollectionBuf != ' ' ||
1617 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1618 (*(startCollectionBuf+3) != ' ' &&
1619 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1620 startCollectionBuf++;
1621 startCollectionBuf += 3;
1622
1623 // Replace: "for (type element in" with string constructed thus far.
1624 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1625 // Replace ')' in for '(' type elem in collection ')' with ';'
1626 SourceLocation rightParenLoc = S->getRParenLoc();
1627 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1628 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1629 buf = ";\n\t";
1630
1631 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1632 // objects:__rw_items count:16];
1633 // which is synthesized into:
1634 // unsigned int limit =
1635 // ((unsigned int (*)
1636 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1637 // (void *)objc_msgSend)((id)l_collection,
1638 // sel_registerName(
1639 // "countByEnumeratingWithState:objects:count:"),
1640 // (struct __objcFastEnumerationState *)&state,
1641 // (id *)__rw_items, (unsigned int)16);
1642 buf += "unsigned long limit =\n\t\t";
1643 SynthCountByEnumWithState(buf);
1644 buf += ";\n\t";
1645 /// if (limit) {
1646 /// unsigned long startMutations = *enumState.mutationsPtr;
1647 /// do {
1648 /// unsigned long counter = 0;
1649 /// do {
1650 /// if (startMutations != *enumState.mutationsPtr)
1651 /// objc_enumerationMutation(l_collection);
1652 /// elem = (type)enumState.itemsPtr[counter++];
1653 buf += "if (limit) {\n\t";
1654 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1655 buf += "do {\n\t\t";
1656 buf += "unsigned long counter = 0;\n\t\t";
1657 buf += "do {\n\t\t\t";
1658 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1659 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1660 buf += elementName;
1661 buf += " = (";
1662 buf += elementTypeAsString;
1663 buf += ")enumState.itemsPtr[counter++];";
1664 // Replace ')' in for '(' type elem in collection ')' with all of these.
1665 ReplaceText(lparenLoc, 1, buf);
1666
1667 /// __continue_label: ;
1668 /// } while (counter < limit);
1669 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1670 /// objects:__rw_items count:16]);
1671 /// elem = nil;
1672 /// __break_label: ;
1673 /// }
1674 /// else
1675 /// elem = nil;
1676 /// }
1677 ///
1678 buf = ";\n\t";
1679 buf += "__continue_label_";
1680 buf += utostr(ObjCBcLabelNo.back());
1681 buf += ": ;";
1682 buf += "\n\t\t";
1683 buf += "} while (counter < limit);\n\t";
1684 buf += "} while (limit = ";
1685 SynthCountByEnumWithState(buf);
1686 buf += ");\n\t";
1687 buf += elementName;
1688 buf += " = ((";
1689 buf += elementTypeAsString;
1690 buf += ")0);\n\t";
1691 buf += "__break_label_";
1692 buf += utostr(ObjCBcLabelNo.back());
1693 buf += ": ;\n\t";
1694 buf += "}\n\t";
1695 buf += "else\n\t\t";
1696 buf += elementName;
1697 buf += " = ((";
1698 buf += elementTypeAsString;
1699 buf += ")0);\n\t";
1700 buf += "}\n";
1701
1702 // Insert all these *after* the statement body.
1703 // FIXME: If this should support Obj-C++, support CXXTryStmt
1704 if (isa<CompoundStmt>(S->getBody())) {
1705 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1706 InsertText(endBodyLoc, buf);
1707 } else {
1708 /* Need to treat single statements specially. For example:
1709 *
1710 * for (A *a in b) if (stuff()) break;
1711 * for (A *a in b) xxxyy;
1712 *
1713 * The following code simply scans ahead to the semi to find the actual end.
1714 */
1715 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1716 const char *semiBuf = strchr(stmtBuf, ';');
1717 assert(semiBuf && "Can't find ';'");
1718 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1719 InsertText(endBodyLoc, buf);
1720 }
1721 Stmts.pop_back();
1722 ObjCBcLabelNo.pop_back();
1723 return 0;
1724}
1725
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001726static void Write_RethrowObject(std::string &buf) {
1727 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1728 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1729 buf += "\tid rethrow;\n";
1730 buf += "\t} _fin_force_rethow(_rethrow);";
1731}
1732
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001733/// RewriteObjCSynchronizedStmt -
1734/// This routine rewrites @synchronized(expr) stmt;
1735/// into:
1736/// objc_sync_enter(expr);
1737/// @try stmt @finally { objc_sync_exit(expr); }
1738///
1739Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1740 // Get the start location and compute the semi location.
1741 SourceLocation startLoc = S->getLocStart();
1742 const char *startBuf = SM->getCharacterData(startLoc);
1743
1744 assert((*startBuf == '@') && "bogus @synchronized location");
1745
1746 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001747 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001748
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001749 const char *lparenBuf = startBuf;
1750 while (*lparenBuf != '(') lparenBuf++;
1751 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001752
1753 buf = "; objc_sync_enter(_sync_obj);\n";
1754 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1755 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1756 buf += "\n\tid sync_exit;";
1757 buf += "\n\t} _sync_exit(_sync_obj);\n";
1758
1759 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1760 // the sync expression is typically a message expression that's already
1761 // been rewritten! (which implies the SourceLocation's are invalid).
1762 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1763 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1764 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1765 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1766
1767 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1768 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1769 assert (*LBraceLocBuf == '{');
1770 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001771
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001772 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001773 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1774 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001775
1776 buf = "} catch (id e) {_rethrow = e;}\n";
1777 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001778 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001779 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001780
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001781 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001782
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001783 return 0;
1784}
1785
1786void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1787{
1788 // Perform a bottom up traversal of all children.
1789 for (Stmt::child_range CI = S->children(); CI; ++CI)
1790 if (*CI)
1791 WarnAboutReturnGotoStmts(*CI);
1792
1793 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1794 Diags.Report(Context->getFullLoc(S->getLocStart()),
1795 TryFinallyContainsReturnDiag);
1796 }
1797 return;
1798}
1799
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001800Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001801 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001802 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001803 std::string buf;
1804
1805 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001806 if (noCatch)
1807 buf = "{ id volatile _rethrow = 0;\n";
1808 else {
1809 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1810 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001811 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001812 // Get the start location and compute the semi location.
1813 SourceLocation startLoc = S->getLocStart();
1814 const char *startBuf = SM->getCharacterData(startLoc);
1815
1816 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001817 if (finalStmt)
1818 ReplaceText(startLoc, 1, buf);
1819 else
1820 // @try -> try
1821 ReplaceText(startLoc, 1, "");
1822
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001823 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1824 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001825 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001826
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001827 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001828 bool AtRemoved = false;
1829 if (catchDecl) {
1830 QualType t = catchDecl->getType();
1831 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1832 // Should be a pointer to a class.
1833 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1834 if (IDecl) {
1835 std::string Result;
1836 startBuf = SM->getCharacterData(startLoc);
1837 assert((*startBuf == '@') && "bogus @catch location");
1838 SourceLocation rParenLoc = Catch->getRParenLoc();
1839 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1840
1841 // _objc_exc_Foo *_e as argument to catch.
1842 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1843 Result += " *_"; Result += catchDecl->getNameAsString();
1844 Result += ")";
1845 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1846 // Foo *e = (Foo *)_e;
1847 Result.clear();
1848 Result = "{ ";
1849 Result += IDecl->getNameAsString();
1850 Result += " *"; Result += catchDecl->getNameAsString();
1851 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1852 Result += "_"; Result += catchDecl->getNameAsString();
1853
1854 Result += "; ";
1855 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1856 ReplaceText(lBraceLoc, 1, Result);
1857 AtRemoved = true;
1858 }
1859 }
1860 }
1861 if (!AtRemoved)
1862 // @catch -> catch
1863 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001864
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001865 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001866 if (finalStmt) {
1867 buf.clear();
1868 if (noCatch)
1869 buf = "catch (id e) {_rethrow = e;}\n";
1870 else
1871 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1872
1873 SourceLocation startFinalLoc = finalStmt->getLocStart();
1874 ReplaceText(startFinalLoc, 8, buf);
1875 Stmt *body = finalStmt->getFinallyBody();
1876 SourceLocation startFinalBodyLoc = body->getLocStart();
1877 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001878 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001879 ReplaceText(startFinalBodyLoc, 1, buf);
1880
1881 SourceLocation endFinalBodyLoc = body->getLocEnd();
1882 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001883 // Now check for any return/continue/go statements within the @try.
1884 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001885 }
1886
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001887 return 0;
1888}
1889
1890// This can't be done with ReplaceStmt(S, ThrowExpr), since
1891// the throw expression is typically a message expression that's already
1892// been rewritten! (which implies the SourceLocation's are invalid).
1893Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1894 // Get the start location and compute the semi location.
1895 SourceLocation startLoc = S->getLocStart();
1896 const char *startBuf = SM->getCharacterData(startLoc);
1897
1898 assert((*startBuf == '@') && "bogus @throw location");
1899
1900 std::string buf;
1901 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1902 if (S->getThrowExpr())
1903 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001904 else
1905 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001906
1907 // handle "@ throw" correctly.
1908 const char *wBuf = strchr(startBuf, 'w');
1909 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1910 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1911
1912 const char *semiBuf = strchr(startBuf, ';');
1913 assert((*semiBuf == ';') && "@throw: can't find ';'");
1914 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001915 if (S->getThrowExpr())
1916 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001917 return 0;
1918}
1919
1920Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1921 // Create a new string expression.
1922 QualType StrType = Context->getPointerType(Context->CharTy);
1923 std::string StrEncoding;
1924 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1925 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1926 StringLiteral::Ascii, false,
1927 StrType, SourceLocation());
1928 ReplaceStmt(Exp, Replacement);
1929
1930 // Replace this subexpr in the parent.
1931 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1932 return Replacement;
1933}
1934
1935Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1936 if (!SelGetUidFunctionDecl)
1937 SynthSelGetUidFunctionDecl();
1938 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1939 // Create a call to sel_registerName("selName").
1940 SmallVector<Expr*, 8> SelExprs;
1941 QualType argType = Context->getPointerType(Context->CharTy);
1942 SelExprs.push_back(StringLiteral::Create(*Context,
1943 Exp->getSelector().getAsString(),
1944 StringLiteral::Ascii, false,
1945 argType, SourceLocation()));
1946 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1947 &SelExprs[0], SelExprs.size());
1948 ReplaceStmt(Exp, SelExp);
1949 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1950 return SelExp;
1951}
1952
1953CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1954 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1955 SourceLocation EndLoc) {
1956 // Get the type, we will need to reference it in a couple spots.
1957 QualType msgSendType = FD->getType();
1958
1959 // Create a reference to the objc_msgSend() declaration.
1960 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001961 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001962
1963 // Now, we cast the reference to a pointer to the objc_msgSend type.
1964 QualType pToFunc = Context->getPointerType(msgSendType);
1965 ImplicitCastExpr *ICE =
1966 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1967 DRE, 0, VK_RValue);
1968
1969 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1970
1971 CallExpr *Exp =
1972 new (Context) CallExpr(*Context, ICE, args, nargs,
1973 FT->getCallResultType(*Context),
1974 VK_RValue, EndLoc);
1975 return Exp;
1976}
1977
1978static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1979 const char *&startRef, const char *&endRef) {
1980 while (startBuf < endBuf) {
1981 if (*startBuf == '<')
1982 startRef = startBuf; // mark the start.
1983 if (*startBuf == '>') {
1984 if (startRef && *startRef == '<') {
1985 endRef = startBuf; // mark the end.
1986 return true;
1987 }
1988 return false;
1989 }
1990 startBuf++;
1991 }
1992 return false;
1993}
1994
1995static void scanToNextArgument(const char *&argRef) {
1996 int angle = 0;
1997 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1998 if (*argRef == '<')
1999 angle++;
2000 else if (*argRef == '>')
2001 angle--;
2002 argRef++;
2003 }
2004 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2005}
2006
2007bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2008 if (T->isObjCQualifiedIdType())
2009 return true;
2010 if (const PointerType *PT = T->getAs<PointerType>()) {
2011 if (PT->getPointeeType()->isObjCQualifiedIdType())
2012 return true;
2013 }
2014 if (T->isObjCObjectPointerType()) {
2015 T = T->getPointeeType();
2016 return T->isObjCQualifiedInterfaceType();
2017 }
2018 if (T->isArrayType()) {
2019 QualType ElemTy = Context->getBaseElementType(T);
2020 return needToScanForQualifiers(ElemTy);
2021 }
2022 return false;
2023}
2024
2025void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2026 QualType Type = E->getType();
2027 if (needToScanForQualifiers(Type)) {
2028 SourceLocation Loc, EndLoc;
2029
2030 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2031 Loc = ECE->getLParenLoc();
2032 EndLoc = ECE->getRParenLoc();
2033 } else {
2034 Loc = E->getLocStart();
2035 EndLoc = E->getLocEnd();
2036 }
2037 // This will defend against trying to rewrite synthesized expressions.
2038 if (Loc.isInvalid() || EndLoc.isInvalid())
2039 return;
2040
2041 const char *startBuf = SM->getCharacterData(Loc);
2042 const char *endBuf = SM->getCharacterData(EndLoc);
2043 const char *startRef = 0, *endRef = 0;
2044 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2045 // Get the locations of the startRef, endRef.
2046 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2047 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2048 // Comment out the protocol references.
2049 InsertText(LessLoc, "/*");
2050 InsertText(GreaterLoc, "*/");
2051 }
2052 }
2053}
2054
2055void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2056 SourceLocation Loc;
2057 QualType Type;
2058 const FunctionProtoType *proto = 0;
2059 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2060 Loc = VD->getLocation();
2061 Type = VD->getType();
2062 }
2063 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2064 Loc = FD->getLocation();
2065 // Check for ObjC 'id' and class types that have been adorned with protocol
2066 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2067 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2068 assert(funcType && "missing function type");
2069 proto = dyn_cast<FunctionProtoType>(funcType);
2070 if (!proto)
2071 return;
2072 Type = proto->getResultType();
2073 }
2074 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2075 Loc = FD->getLocation();
2076 Type = FD->getType();
2077 }
2078 else
2079 return;
2080
2081 if (needToScanForQualifiers(Type)) {
2082 // Since types are unique, we need to scan the buffer.
2083
2084 const char *endBuf = SM->getCharacterData(Loc);
2085 const char *startBuf = endBuf;
2086 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2087 startBuf--; // scan backward (from the decl location) for return type.
2088 const char *startRef = 0, *endRef = 0;
2089 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2090 // Get the locations of the startRef, endRef.
2091 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2092 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2093 // Comment out the protocol references.
2094 InsertText(LessLoc, "/*");
2095 InsertText(GreaterLoc, "*/");
2096 }
2097 }
2098 if (!proto)
2099 return; // most likely, was a variable
2100 // Now check arguments.
2101 const char *startBuf = SM->getCharacterData(Loc);
2102 const char *startFuncBuf = startBuf;
2103 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2104 if (needToScanForQualifiers(proto->getArgType(i))) {
2105 // Since types are unique, we need to scan the buffer.
2106
2107 const char *endBuf = startBuf;
2108 // scan forward (from the decl location) for argument types.
2109 scanToNextArgument(endBuf);
2110 const char *startRef = 0, *endRef = 0;
2111 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2112 // Get the locations of the startRef, endRef.
2113 SourceLocation LessLoc =
2114 Loc.getLocWithOffset(startRef-startFuncBuf);
2115 SourceLocation GreaterLoc =
2116 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2117 // Comment out the protocol references.
2118 InsertText(LessLoc, "/*");
2119 InsertText(GreaterLoc, "*/");
2120 }
2121 startBuf = ++endBuf;
2122 }
2123 else {
2124 // If the function name is derived from a macro expansion, then the
2125 // argument buffer will not follow the name. Need to speak with Chris.
2126 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2127 startBuf++; // scan forward (from the decl location) for argument types.
2128 startBuf++;
2129 }
2130 }
2131}
2132
2133void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2134 QualType QT = ND->getType();
2135 const Type* TypePtr = QT->getAs<Type>();
2136 if (!isa<TypeOfExprType>(TypePtr))
2137 return;
2138 while (isa<TypeOfExprType>(TypePtr)) {
2139 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2140 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2141 TypePtr = QT->getAs<Type>();
2142 }
2143 // FIXME. This will not work for multiple declarators; as in:
2144 // __typeof__(a) b,c,d;
2145 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2146 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2147 const char *startBuf = SM->getCharacterData(DeclLoc);
2148 if (ND->getInit()) {
2149 std::string Name(ND->getNameAsString());
2150 TypeAsString += " " + Name + " = ";
2151 Expr *E = ND->getInit();
2152 SourceLocation startLoc;
2153 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2154 startLoc = ECE->getLParenLoc();
2155 else
2156 startLoc = E->getLocStart();
2157 startLoc = SM->getExpansionLoc(startLoc);
2158 const char *endBuf = SM->getCharacterData(startLoc);
2159 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2160 }
2161 else {
2162 SourceLocation X = ND->getLocEnd();
2163 X = SM->getExpansionLoc(X);
2164 const char *endBuf = SM->getCharacterData(X);
2165 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2166 }
2167}
2168
2169// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2170void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2171 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2172 SmallVector<QualType, 16> ArgTys;
2173 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2174 QualType getFuncType =
2175 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2176 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2177 SourceLocation(),
2178 SourceLocation(),
2179 SelGetUidIdent, getFuncType, 0,
2180 SC_Extern,
2181 SC_None, false);
2182}
2183
2184void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2185 // declared in <objc/objc.h>
2186 if (FD->getIdentifier() &&
2187 FD->getName() == "sel_registerName") {
2188 SelGetUidFunctionDecl = FD;
2189 return;
2190 }
2191 RewriteObjCQualifiedInterfaceTypes(FD);
2192}
2193
2194void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2195 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2196 const char *argPtr = TypeString.c_str();
2197 if (!strchr(argPtr, '^')) {
2198 Str += TypeString;
2199 return;
2200 }
2201 while (*argPtr) {
2202 Str += (*argPtr == '^' ? '*' : *argPtr);
2203 argPtr++;
2204 }
2205}
2206
2207// FIXME. Consolidate this routine with RewriteBlockPointerType.
2208void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2209 ValueDecl *VD) {
2210 QualType Type = VD->getType();
2211 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2212 const char *argPtr = TypeString.c_str();
2213 int paren = 0;
2214 while (*argPtr) {
2215 switch (*argPtr) {
2216 case '(':
2217 Str += *argPtr;
2218 paren++;
2219 break;
2220 case ')':
2221 Str += *argPtr;
2222 paren--;
2223 break;
2224 case '^':
2225 Str += '*';
2226 if (paren == 1)
2227 Str += VD->getNameAsString();
2228 break;
2229 default:
2230 Str += *argPtr;
2231 break;
2232 }
2233 argPtr++;
2234 }
2235}
2236
2237
2238void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2239 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2240 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2241 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2242 if (!proto)
2243 return;
2244 QualType Type = proto->getResultType();
2245 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2246 FdStr += " ";
2247 FdStr += FD->getName();
2248 FdStr += "(";
2249 unsigned numArgs = proto->getNumArgs();
2250 for (unsigned i = 0; i < numArgs; i++) {
2251 QualType ArgType = proto->getArgType(i);
2252 RewriteBlockPointerType(FdStr, ArgType);
2253 if (i+1 < numArgs)
2254 FdStr += ", ";
2255 }
2256 FdStr += ");\n";
2257 InsertText(FunLocStart, FdStr);
2258 CurFunctionDeclToDeclareForBlock = 0;
2259}
2260
2261// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2262void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2263 if (SuperContructorFunctionDecl)
2264 return;
2265 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2266 SmallVector<QualType, 16> ArgTys;
2267 QualType argT = Context->getObjCIdType();
2268 assert(!argT.isNull() && "Can't find 'id' type");
2269 ArgTys.push_back(argT);
2270 ArgTys.push_back(argT);
2271 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2272 &ArgTys[0], ArgTys.size());
2273 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2274 SourceLocation(),
2275 SourceLocation(),
2276 msgSendIdent, msgSendType, 0,
2277 SC_Extern,
2278 SC_None, false);
2279}
2280
2281// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2282void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2283 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2284 SmallVector<QualType, 16> ArgTys;
2285 QualType argT = Context->getObjCIdType();
2286 assert(!argT.isNull() && "Can't find 'id' type");
2287 ArgTys.push_back(argT);
2288 argT = Context->getObjCSelType();
2289 assert(!argT.isNull() && "Can't find 'SEL' type");
2290 ArgTys.push_back(argT);
2291 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2292 &ArgTys[0], ArgTys.size(),
2293 true /*isVariadic*/);
2294 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2295 SourceLocation(),
2296 SourceLocation(),
2297 msgSendIdent, msgSendType, 0,
2298 SC_Extern,
2299 SC_None, false);
2300}
2301
2302// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2303void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2304 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2305 SmallVector<QualType, 16> ArgTys;
2306 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2307 SourceLocation(), SourceLocation(),
2308 &Context->Idents.get("objc_super"));
2309 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2310 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2311 ArgTys.push_back(argT);
2312 argT = Context->getObjCSelType();
2313 assert(!argT.isNull() && "Can't find 'SEL' type");
2314 ArgTys.push_back(argT);
2315 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2316 &ArgTys[0], ArgTys.size(),
2317 true /*isVariadic*/);
2318 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319 SourceLocation(),
2320 SourceLocation(),
2321 msgSendIdent, msgSendType, 0,
2322 SC_Extern,
2323 SC_None, false);
2324}
2325
2326// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2327void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2328 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2329 SmallVector<QualType, 16> ArgTys;
2330 QualType argT = Context->getObjCIdType();
2331 assert(!argT.isNull() && "Can't find 'id' type");
2332 ArgTys.push_back(argT);
2333 argT = Context->getObjCSelType();
2334 assert(!argT.isNull() && "Can't find 'SEL' type");
2335 ArgTys.push_back(argT);
2336 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2337 &ArgTys[0], ArgTys.size(),
2338 true /*isVariadic*/);
2339 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2340 SourceLocation(),
2341 SourceLocation(),
2342 msgSendIdent, msgSendType, 0,
2343 SC_Extern,
2344 SC_None, false);
2345}
2346
2347// SynthMsgSendSuperStretFunctionDecl -
2348// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2349void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2350 IdentifierInfo *msgSendIdent =
2351 &Context->Idents.get("objc_msgSendSuper_stret");
2352 SmallVector<QualType, 16> ArgTys;
2353 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2354 SourceLocation(), SourceLocation(),
2355 &Context->Idents.get("objc_super"));
2356 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2357 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2358 ArgTys.push_back(argT);
2359 argT = Context->getObjCSelType();
2360 assert(!argT.isNull() && "Can't find 'SEL' type");
2361 ArgTys.push_back(argT);
2362 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2363 &ArgTys[0], ArgTys.size(),
2364 true /*isVariadic*/);
2365 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2366 SourceLocation(),
2367 SourceLocation(),
2368 msgSendIdent, msgSendType, 0,
2369 SC_Extern,
2370 SC_None, false);
2371}
2372
2373// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2374void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2375 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2376 SmallVector<QualType, 16> ArgTys;
2377 QualType argT = Context->getObjCIdType();
2378 assert(!argT.isNull() && "Can't find 'id' type");
2379 ArgTys.push_back(argT);
2380 argT = Context->getObjCSelType();
2381 assert(!argT.isNull() && "Can't find 'SEL' type");
2382 ArgTys.push_back(argT);
2383 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2384 &ArgTys[0], ArgTys.size(),
2385 true /*isVariadic*/);
2386 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2387 SourceLocation(),
2388 SourceLocation(),
2389 msgSendIdent, msgSendType, 0,
2390 SC_Extern,
2391 SC_None, false);
2392}
2393
2394// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2395void RewriteModernObjC::SynthGetClassFunctionDecl() {
2396 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2397 SmallVector<QualType, 16> ArgTys;
2398 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2399 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2400 &ArgTys[0], ArgTys.size());
2401 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2402 SourceLocation(),
2403 SourceLocation(),
2404 getClassIdent, getClassType, 0,
2405 SC_Extern,
2406 SC_None, false);
2407}
2408
2409// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2410void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2411 IdentifierInfo *getSuperClassIdent =
2412 &Context->Idents.get("class_getSuperclass");
2413 SmallVector<QualType, 16> ArgTys;
2414 ArgTys.push_back(Context->getObjCClassType());
2415 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2416 &ArgTys[0], ArgTys.size());
2417 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2418 SourceLocation(),
2419 SourceLocation(),
2420 getSuperClassIdent,
2421 getClassType, 0,
2422 SC_Extern,
2423 SC_None,
2424 false);
2425}
2426
2427// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2428void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2429 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2430 SmallVector<QualType, 16> ArgTys;
2431 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2432 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2433 &ArgTys[0], ArgTys.size());
2434 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2435 SourceLocation(),
2436 SourceLocation(),
2437 getClassIdent, getClassType, 0,
2438 SC_Extern,
2439 SC_None, false);
2440}
2441
2442Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2443 QualType strType = getConstantStringStructType();
2444
2445 std::string S = "__NSConstantStringImpl_";
2446
2447 std::string tmpName = InFileName;
2448 unsigned i;
2449 for (i=0; i < tmpName.length(); i++) {
2450 char c = tmpName.at(i);
2451 // replace any non alphanumeric characters with '_'.
2452 if (!isalpha(c) && (c < '0' || c > '9'))
2453 tmpName[i] = '_';
2454 }
2455 S += tmpName;
2456 S += "_";
2457 S += utostr(NumObjCStringLiterals++);
2458
2459 Preamble += "static __NSConstantStringImpl " + S;
2460 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2461 Preamble += "0x000007c8,"; // utf8_str
2462 // The pretty printer for StringLiteral handles escape characters properly.
2463 std::string prettyBufS;
2464 llvm::raw_string_ostream prettyBuf(prettyBufS);
2465 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2466 PrintingPolicy(LangOpts));
2467 Preamble += prettyBuf.str();
2468 Preamble += ",";
2469 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2470
2471 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2472 SourceLocation(), &Context->Idents.get(S),
2473 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002474 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002475 SourceLocation());
2476 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2477 Context->getPointerType(DRE->getType()),
2478 VK_RValue, OK_Ordinary,
2479 SourceLocation());
2480 // cast to NSConstantString *
2481 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2482 CK_CPointerToObjCPointerCast, Unop);
2483 ReplaceStmt(Exp, cast);
2484 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2485 return cast;
2486}
2487
Fariborz Jahanian55947042012-03-27 20:17:30 +00002488Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2489 unsigned IntSize =
2490 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2491
2492 Expr *FlagExp = IntegerLiteral::Create(*Context,
2493 llvm::APInt(IntSize, Exp->getValue()),
2494 Context->IntTy, Exp->getLocation());
2495 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2496 CK_BitCast, FlagExp);
2497 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2498 cast);
2499 ReplaceStmt(Exp, PE);
2500 return PE;
2501}
2502
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002503Stmt *RewriteModernObjC::RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp) {
2504 // synthesize declaration of helper functions needed in this routine.
2505 if (!SelGetUidFunctionDecl)
2506 SynthSelGetUidFunctionDecl();
2507 // use objc_msgSend() for all.
2508 if (!MsgSendFunctionDecl)
2509 SynthMsgSendFunctionDecl();
2510 if (!GetClassFunctionDecl)
2511 SynthGetClassFunctionDecl();
2512
2513 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2514 SourceLocation StartLoc = Exp->getLocStart();
2515 SourceLocation EndLoc = Exp->getLocEnd();
2516
2517 // Synthesize a call to objc_msgSend().
2518 SmallVector<Expr*, 4> MsgExprs;
2519 SmallVector<Expr*, 4> ClsExprs;
2520 QualType argType = Context->getPointerType(Context->CharTy);
2521 QualType expType = Exp->getType();
2522
2523 // Create a call to objc_getClass("NSNumber"). It will be th 1st argument.
2524 ObjCInterfaceDecl *Class =
2525 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2526
2527 IdentifierInfo *clsName = Class->getIdentifier();
2528 ClsExprs.push_back(StringLiteral::Create(*Context,
2529 clsName->getName(),
2530 StringLiteral::Ascii, false,
2531 argType, SourceLocation()));
2532 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2533 &ClsExprs[0],
2534 ClsExprs.size(),
2535 StartLoc, EndLoc);
2536 MsgExprs.push_back(Cls);
2537
2538 // Create a call to sel_registerName("numberWithBool:"), etc.
2539 // it will be the 2nd argument.
2540 SmallVector<Expr*, 4> SelExprs;
2541 ObjCMethodDecl *NumericMethod = Exp->getObjCNumericLiteralMethod();
2542 SelExprs.push_back(StringLiteral::Create(*Context,
2543 NumericMethod->getSelector().getAsString(),
2544 StringLiteral::Ascii, false,
2545 argType, SourceLocation()));
2546 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2547 &SelExprs[0], SelExprs.size(),
2548 StartLoc, EndLoc);
2549 MsgExprs.push_back(SelExp);
2550
2551 // User provided numeric literal is the 3rd, and last, argument.
2552 Expr *userExpr = Exp->getNumber();
2553 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2554 QualType type = ICE->getType();
2555 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2556 CastKind CK = CK_BitCast;
2557 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2558 CK = CK_IntegralToBoolean;
2559 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2560 }
2561 MsgExprs.push_back(userExpr);
2562
2563 SmallVector<QualType, 4> ArgTypes;
2564 ArgTypes.push_back(Context->getObjCIdType());
2565 ArgTypes.push_back(Context->getObjCSelType());
2566 for (ObjCMethodDecl::param_iterator PI = NumericMethod->param_begin(),
2567 E = NumericMethod->param_end(); PI != E; ++PI)
2568 ArgTypes.push_back((*PI)->getType());
2569
2570 QualType returnType = Exp->getType();
2571 // Get the type, we will need to reference it in a couple spots.
2572 QualType msgSendType = MsgSendFlavor->getType();
2573
2574 // Create a reference to the objc_msgSend() declaration.
2575 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2576 VK_LValue, SourceLocation());
2577
2578 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2579 Context->getPointerType(Context->VoidTy),
2580 CK_BitCast, DRE);
2581
2582 // Now do the "normal" pointer to function cast.
2583 QualType castType =
2584 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2585 NumericMethod->isVariadic());
2586 castType = Context->getPointerType(castType);
2587 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2588 cast);
2589
2590 // Don't forget the parens to enforce the proper binding.
2591 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2592
2593 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2594 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2595 MsgExprs.size(),
2596 FT->getResultType(), VK_RValue,
2597 EndLoc);
2598 ReplaceStmt(Exp, CE);
2599 return CE;
2600}
2601
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002602Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2603 // synthesize declaration of helper functions needed in this routine.
2604 if (!SelGetUidFunctionDecl)
2605 SynthSelGetUidFunctionDecl();
2606 // use objc_msgSend() for all.
2607 if (!MsgSendFunctionDecl)
2608 SynthMsgSendFunctionDecl();
2609 if (!GetClassFunctionDecl)
2610 SynthGetClassFunctionDecl();
2611
2612 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2613 SourceLocation StartLoc = Exp->getLocStart();
2614 SourceLocation EndLoc = Exp->getLocEnd();
2615
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002616 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002617 QualType IntQT = Context->IntTy;
2618 QualType NSArrayFType =
2619 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002620 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002621 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2622 DeclRefExpr *NSArrayDRE =
2623 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2624 SourceLocation());
2625
2626 SmallVector<Expr*, 16> InitExprs;
2627 unsigned NumElements = Exp->getNumElements();
2628 unsigned UnsignedIntSize =
2629 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2630 Expr *count = IntegerLiteral::Create(*Context,
2631 llvm::APInt(UnsignedIntSize, NumElements),
2632 Context->UnsignedIntTy, SourceLocation());
2633 InitExprs.push_back(count);
2634 for (unsigned i = 0; i < NumElements; i++)
2635 InitExprs.push_back(Exp->getElement(i));
2636 Expr *NSArrayCallExpr =
2637 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2638 NSArrayFType, VK_LValue, SourceLocation());
2639
2640 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2641 SourceLocation(),
2642 &Context->Idents.get("arr"),
2643 Context->getPointerType(Context->VoidPtrTy), 0,
2644 /*BitWidth=*/0, /*Mutable=*/true,
2645 /*HasInit=*/false);
2646 MemberExpr *ArrayLiteralME =
2647 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2648 SourceLocation(),
2649 ARRFD->getType(), VK_LValue,
2650 OK_Ordinary);
2651 QualType ConstIdT = Context->getObjCIdType().withConst();
2652 CStyleCastExpr * ArrayLiteralObjects =
2653 NoTypeInfoCStyleCastExpr(Context,
2654 Context->getPointerType(ConstIdT),
2655 CK_BitCast,
2656 ArrayLiteralME);
2657
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002658 // Synthesize a call to objc_msgSend().
2659 SmallVector<Expr*, 32> MsgExprs;
2660 SmallVector<Expr*, 4> ClsExprs;
2661 QualType argType = Context->getPointerType(Context->CharTy);
2662 QualType expType = Exp->getType();
2663
2664 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2665 ObjCInterfaceDecl *Class =
2666 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2667
2668 IdentifierInfo *clsName = Class->getIdentifier();
2669 ClsExprs.push_back(StringLiteral::Create(*Context,
2670 clsName->getName(),
2671 StringLiteral::Ascii, false,
2672 argType, SourceLocation()));
2673 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2674 &ClsExprs[0],
2675 ClsExprs.size(),
2676 StartLoc, EndLoc);
2677 MsgExprs.push_back(Cls);
2678
2679 // Create a call to sel_registerName("arrayWithObjects:count:").
2680 // it will be the 2nd argument.
2681 SmallVector<Expr*, 4> SelExprs;
2682 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2683 SelExprs.push_back(StringLiteral::Create(*Context,
2684 ArrayMethod->getSelector().getAsString(),
2685 StringLiteral::Ascii, false,
2686 argType, SourceLocation()));
2687 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2688 &SelExprs[0], SelExprs.size(),
2689 StartLoc, EndLoc);
2690 MsgExprs.push_back(SelExp);
2691
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002692 // (const id [])objects
2693 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002694
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002695 // (NSUInteger)cnt
2696 Expr *cnt = IntegerLiteral::Create(*Context,
2697 llvm::APInt(UnsignedIntSize, NumElements),
2698 Context->UnsignedIntTy, SourceLocation());
2699 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002700
2701
2702 SmallVector<QualType, 4> ArgTypes;
2703 ArgTypes.push_back(Context->getObjCIdType());
2704 ArgTypes.push_back(Context->getObjCSelType());
2705 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2706 E = ArrayMethod->param_end(); PI != E; ++PI)
2707 ArgTypes.push_back((*PI)->getType());
2708
2709 QualType returnType = Exp->getType();
2710 // Get the type, we will need to reference it in a couple spots.
2711 QualType msgSendType = MsgSendFlavor->getType();
2712
2713 // Create a reference to the objc_msgSend() declaration.
2714 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2715 VK_LValue, SourceLocation());
2716
2717 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2718 Context->getPointerType(Context->VoidTy),
2719 CK_BitCast, DRE);
2720
2721 // Now do the "normal" pointer to function cast.
2722 QualType castType =
2723 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2724 ArrayMethod->isVariadic());
2725 castType = Context->getPointerType(castType);
2726 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2727 cast);
2728
2729 // Don't forget the parens to enforce the proper binding.
2730 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2731
2732 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2733 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2734 MsgExprs.size(),
2735 FT->getResultType(), VK_RValue,
2736 EndLoc);
2737 ReplaceStmt(Exp, CE);
2738 return CE;
2739}
2740
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002741Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2742 // synthesize declaration of helper functions needed in this routine.
2743 if (!SelGetUidFunctionDecl)
2744 SynthSelGetUidFunctionDecl();
2745 // use objc_msgSend() for all.
2746 if (!MsgSendFunctionDecl)
2747 SynthMsgSendFunctionDecl();
2748 if (!GetClassFunctionDecl)
2749 SynthGetClassFunctionDecl();
2750
2751 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2752 SourceLocation StartLoc = Exp->getLocStart();
2753 SourceLocation EndLoc = Exp->getLocEnd();
2754
2755 // Build the expression: __NSContainer_literal(int, ...).arr
2756 QualType IntQT = Context->IntTy;
2757 QualType NSDictFType =
2758 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2759 std::string NSDictFName("__NSContainer_literal");
2760 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2761 DeclRefExpr *NSDictDRE =
2762 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2763 SourceLocation());
2764
2765 SmallVector<Expr*, 16> KeyExprs;
2766 SmallVector<Expr*, 16> ValueExprs;
2767
2768 unsigned NumElements = Exp->getNumElements();
2769 unsigned UnsignedIntSize =
2770 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2771 Expr *count = IntegerLiteral::Create(*Context,
2772 llvm::APInt(UnsignedIntSize, NumElements),
2773 Context->UnsignedIntTy, SourceLocation());
2774 KeyExprs.push_back(count);
2775 ValueExprs.push_back(count);
2776 for (unsigned i = 0; i < NumElements; i++) {
2777 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2778 KeyExprs.push_back(Element.Key);
2779 ValueExprs.push_back(Element.Value);
2780 }
2781
2782 // (const id [])objects
2783 Expr *NSValueCallExpr =
2784 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2785 NSDictFType, VK_LValue, SourceLocation());
2786
2787 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2788 SourceLocation(),
2789 &Context->Idents.get("arr"),
2790 Context->getPointerType(Context->VoidPtrTy), 0,
2791 /*BitWidth=*/0, /*Mutable=*/true,
2792 /*HasInit=*/false);
2793 MemberExpr *DictLiteralValueME =
2794 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2795 SourceLocation(),
2796 ARRFD->getType(), VK_LValue,
2797 OK_Ordinary);
2798 QualType ConstIdT = Context->getObjCIdType().withConst();
2799 CStyleCastExpr * DictValueObjects =
2800 NoTypeInfoCStyleCastExpr(Context,
2801 Context->getPointerType(ConstIdT),
2802 CK_BitCast,
2803 DictLiteralValueME);
2804 // (const id <NSCopying> [])keys
2805 Expr *NSKeyCallExpr =
2806 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2807 NSDictFType, VK_LValue, SourceLocation());
2808
2809 MemberExpr *DictLiteralKeyME =
2810 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2811 SourceLocation(),
2812 ARRFD->getType(), VK_LValue,
2813 OK_Ordinary);
2814
2815 CStyleCastExpr * DictKeyObjects =
2816 NoTypeInfoCStyleCastExpr(Context,
2817 Context->getPointerType(ConstIdT),
2818 CK_BitCast,
2819 DictLiteralKeyME);
2820
2821
2822
2823 // Synthesize a call to objc_msgSend().
2824 SmallVector<Expr*, 32> MsgExprs;
2825 SmallVector<Expr*, 4> ClsExprs;
2826 QualType argType = Context->getPointerType(Context->CharTy);
2827 QualType expType = Exp->getType();
2828
2829 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2830 ObjCInterfaceDecl *Class =
2831 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2832
2833 IdentifierInfo *clsName = Class->getIdentifier();
2834 ClsExprs.push_back(StringLiteral::Create(*Context,
2835 clsName->getName(),
2836 StringLiteral::Ascii, false,
2837 argType, SourceLocation()));
2838 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2839 &ClsExprs[0],
2840 ClsExprs.size(),
2841 StartLoc, EndLoc);
2842 MsgExprs.push_back(Cls);
2843
2844 // Create a call to sel_registerName("arrayWithObjects:count:").
2845 // it will be the 2nd argument.
2846 SmallVector<Expr*, 4> SelExprs;
2847 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2848 SelExprs.push_back(StringLiteral::Create(*Context,
2849 DictMethod->getSelector().getAsString(),
2850 StringLiteral::Ascii, false,
2851 argType, SourceLocation()));
2852 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2853 &SelExprs[0], SelExprs.size(),
2854 StartLoc, EndLoc);
2855 MsgExprs.push_back(SelExp);
2856
2857 // (const id [])objects
2858 MsgExprs.push_back(DictValueObjects);
2859
2860 // (const id <NSCopying> [])keys
2861 MsgExprs.push_back(DictKeyObjects);
2862
2863 // (NSUInteger)cnt
2864 Expr *cnt = IntegerLiteral::Create(*Context,
2865 llvm::APInt(UnsignedIntSize, NumElements),
2866 Context->UnsignedIntTy, SourceLocation());
2867 MsgExprs.push_back(cnt);
2868
2869
2870 SmallVector<QualType, 8> ArgTypes;
2871 ArgTypes.push_back(Context->getObjCIdType());
2872 ArgTypes.push_back(Context->getObjCSelType());
2873 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2874 E = DictMethod->param_end(); PI != E; ++PI) {
2875 QualType T = (*PI)->getType();
2876 if (const PointerType* PT = T->getAs<PointerType>()) {
2877 QualType PointeeTy = PT->getPointeeType();
2878 convertToUnqualifiedObjCType(PointeeTy);
2879 T = Context->getPointerType(PointeeTy);
2880 }
2881 ArgTypes.push_back(T);
2882 }
2883
2884 QualType returnType = Exp->getType();
2885 // Get the type, we will need to reference it in a couple spots.
2886 QualType msgSendType = MsgSendFlavor->getType();
2887
2888 // Create a reference to the objc_msgSend() declaration.
2889 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2890 VK_LValue, SourceLocation());
2891
2892 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2893 Context->getPointerType(Context->VoidTy),
2894 CK_BitCast, DRE);
2895
2896 // Now do the "normal" pointer to function cast.
2897 QualType castType =
2898 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2899 DictMethod->isVariadic());
2900 castType = Context->getPointerType(castType);
2901 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2902 cast);
2903
2904 // Don't forget the parens to enforce the proper binding.
2905 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2906
2907 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2908 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2909 MsgExprs.size(),
2910 FT->getResultType(), VK_RValue,
2911 EndLoc);
2912 ReplaceStmt(Exp, CE);
2913 return CE;
2914}
2915
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002916// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2917QualType RewriteModernObjC::getSuperStructType() {
2918 if (!SuperStructDecl) {
2919 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2920 SourceLocation(), SourceLocation(),
2921 &Context->Idents.get("objc_super"));
2922 QualType FieldTypes[2];
2923
2924 // struct objc_object *receiver;
2925 FieldTypes[0] = Context->getObjCIdType();
2926 // struct objc_class *super;
2927 FieldTypes[1] = Context->getObjCClassType();
2928
2929 // Create fields
2930 for (unsigned i = 0; i < 2; ++i) {
2931 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2932 SourceLocation(),
2933 SourceLocation(), 0,
2934 FieldTypes[i], 0,
2935 /*BitWidth=*/0,
2936 /*Mutable=*/false,
2937 /*HasInit=*/false));
2938 }
2939
2940 SuperStructDecl->completeDefinition();
2941 }
2942 return Context->getTagDeclType(SuperStructDecl);
2943}
2944
2945QualType RewriteModernObjC::getConstantStringStructType() {
2946 if (!ConstantStringDecl) {
2947 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2948 SourceLocation(), SourceLocation(),
2949 &Context->Idents.get("__NSConstantStringImpl"));
2950 QualType FieldTypes[4];
2951
2952 // struct objc_object *receiver;
2953 FieldTypes[0] = Context->getObjCIdType();
2954 // int flags;
2955 FieldTypes[1] = Context->IntTy;
2956 // char *str;
2957 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2958 // long length;
2959 FieldTypes[3] = Context->LongTy;
2960
2961 // Create fields
2962 for (unsigned i = 0; i < 4; ++i) {
2963 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2964 ConstantStringDecl,
2965 SourceLocation(),
2966 SourceLocation(), 0,
2967 FieldTypes[i], 0,
2968 /*BitWidth=*/0,
2969 /*Mutable=*/true,
2970 /*HasInit=*/false));
2971 }
2972
2973 ConstantStringDecl->completeDefinition();
2974 }
2975 return Context->getTagDeclType(ConstantStringDecl);
2976}
2977
2978Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2979 SourceLocation StartLoc,
2980 SourceLocation EndLoc) {
2981 if (!SelGetUidFunctionDecl)
2982 SynthSelGetUidFunctionDecl();
2983 if (!MsgSendFunctionDecl)
2984 SynthMsgSendFunctionDecl();
2985 if (!MsgSendSuperFunctionDecl)
2986 SynthMsgSendSuperFunctionDecl();
2987 if (!MsgSendStretFunctionDecl)
2988 SynthMsgSendStretFunctionDecl();
2989 if (!MsgSendSuperStretFunctionDecl)
2990 SynthMsgSendSuperStretFunctionDecl();
2991 if (!MsgSendFpretFunctionDecl)
2992 SynthMsgSendFpretFunctionDecl();
2993 if (!GetClassFunctionDecl)
2994 SynthGetClassFunctionDecl();
2995 if (!GetSuperClassFunctionDecl)
2996 SynthGetSuperClassFunctionDecl();
2997 if (!GetMetaClassFunctionDecl)
2998 SynthGetMetaClassFunctionDecl();
2999
3000 // default to objc_msgSend().
3001 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3002 // May need to use objc_msgSend_stret() as well.
3003 FunctionDecl *MsgSendStretFlavor = 0;
3004 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3005 QualType resultType = mDecl->getResultType();
3006 if (resultType->isRecordType())
3007 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3008 else if (resultType->isRealFloatingType())
3009 MsgSendFlavor = MsgSendFpretFunctionDecl;
3010 }
3011
3012 // Synthesize a call to objc_msgSend().
3013 SmallVector<Expr*, 8> MsgExprs;
3014 switch (Exp->getReceiverKind()) {
3015 case ObjCMessageExpr::SuperClass: {
3016 MsgSendFlavor = MsgSendSuperFunctionDecl;
3017 if (MsgSendStretFlavor)
3018 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3019 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3020
3021 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3022
3023 SmallVector<Expr*, 4> InitExprs;
3024
3025 // set the receiver to self, the first argument to all methods.
3026 InitExprs.push_back(
3027 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3028 CK_BitCast,
3029 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003030 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003031 Context->getObjCIdType(),
3032 VK_RValue,
3033 SourceLocation()))
3034 ); // set the 'receiver'.
3035
3036 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3037 SmallVector<Expr*, 8> ClsExprs;
3038 QualType argType = Context->getPointerType(Context->CharTy);
3039 ClsExprs.push_back(StringLiteral::Create(*Context,
3040 ClassDecl->getIdentifier()->getName(),
3041 StringLiteral::Ascii, false,
3042 argType, SourceLocation()));
3043 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3044 &ClsExprs[0],
3045 ClsExprs.size(),
3046 StartLoc,
3047 EndLoc);
3048 // (Class)objc_getClass("CurrentClass")
3049 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3050 Context->getObjCClassType(),
3051 CK_BitCast, Cls);
3052 ClsExprs.clear();
3053 ClsExprs.push_back(ArgExpr);
3054 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3055 &ClsExprs[0], ClsExprs.size(),
3056 StartLoc, EndLoc);
3057
3058 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3059 // To turn off a warning, type-cast to 'id'
3060 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3061 NoTypeInfoCStyleCastExpr(Context,
3062 Context->getObjCIdType(),
3063 CK_BitCast, Cls));
3064 // struct objc_super
3065 QualType superType = getSuperStructType();
3066 Expr *SuperRep;
3067
3068 if (LangOpts.MicrosoftExt) {
3069 SynthSuperContructorFunctionDecl();
3070 // Simulate a contructor call...
3071 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003072 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003073 SourceLocation());
3074 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3075 InitExprs.size(),
3076 superType, VK_LValue,
3077 SourceLocation());
3078 // The code for super is a little tricky to prevent collision with
3079 // the structure definition in the header. The rewriter has it's own
3080 // internal definition (__rw_objc_super) that is uses. This is why
3081 // we need the cast below. For example:
3082 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3083 //
3084 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3085 Context->getPointerType(SuperRep->getType()),
3086 VK_RValue, OK_Ordinary,
3087 SourceLocation());
3088 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3089 Context->getPointerType(superType),
3090 CK_BitCast, SuperRep);
3091 } else {
3092 // (struct objc_super) { <exprs from above> }
3093 InitListExpr *ILE =
3094 new (Context) InitListExpr(*Context, SourceLocation(),
3095 &InitExprs[0], InitExprs.size(),
3096 SourceLocation());
3097 TypeSourceInfo *superTInfo
3098 = Context->getTrivialTypeSourceInfo(superType);
3099 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3100 superType, VK_LValue,
3101 ILE, false);
3102 // struct objc_super *
3103 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3104 Context->getPointerType(SuperRep->getType()),
3105 VK_RValue, OK_Ordinary,
3106 SourceLocation());
3107 }
3108 MsgExprs.push_back(SuperRep);
3109 break;
3110 }
3111
3112 case ObjCMessageExpr::Class: {
3113 SmallVector<Expr*, 8> ClsExprs;
3114 QualType argType = Context->getPointerType(Context->CharTy);
3115 ObjCInterfaceDecl *Class
3116 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3117 IdentifierInfo *clsName = Class->getIdentifier();
3118 ClsExprs.push_back(StringLiteral::Create(*Context,
3119 clsName->getName(),
3120 StringLiteral::Ascii, false,
3121 argType, SourceLocation()));
3122 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3123 &ClsExprs[0],
3124 ClsExprs.size(),
3125 StartLoc, EndLoc);
3126 MsgExprs.push_back(Cls);
3127 break;
3128 }
3129
3130 case ObjCMessageExpr::SuperInstance:{
3131 MsgSendFlavor = MsgSendSuperFunctionDecl;
3132 if (MsgSendStretFlavor)
3133 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3134 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3135 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3136 SmallVector<Expr*, 4> InitExprs;
3137
3138 InitExprs.push_back(
3139 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3140 CK_BitCast,
3141 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003142 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003143 Context->getObjCIdType(),
3144 VK_RValue, SourceLocation()))
3145 ); // set the 'receiver'.
3146
3147 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3148 SmallVector<Expr*, 8> ClsExprs;
3149 QualType argType = Context->getPointerType(Context->CharTy);
3150 ClsExprs.push_back(StringLiteral::Create(*Context,
3151 ClassDecl->getIdentifier()->getName(),
3152 StringLiteral::Ascii, false, argType,
3153 SourceLocation()));
3154 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3155 &ClsExprs[0],
3156 ClsExprs.size(),
3157 StartLoc, EndLoc);
3158 // (Class)objc_getClass("CurrentClass")
3159 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3160 Context->getObjCClassType(),
3161 CK_BitCast, Cls);
3162 ClsExprs.clear();
3163 ClsExprs.push_back(ArgExpr);
3164 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3165 &ClsExprs[0], ClsExprs.size(),
3166 StartLoc, EndLoc);
3167
3168 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3169 // To turn off a warning, type-cast to 'id'
3170 InitExprs.push_back(
3171 // set 'super class', using class_getSuperclass().
3172 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3173 CK_BitCast, Cls));
3174 // struct objc_super
3175 QualType superType = getSuperStructType();
3176 Expr *SuperRep;
3177
3178 if (LangOpts.MicrosoftExt) {
3179 SynthSuperContructorFunctionDecl();
3180 // Simulate a contructor call...
3181 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003182 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003183 SourceLocation());
3184 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3185 InitExprs.size(),
3186 superType, VK_LValue, SourceLocation());
3187 // The code for super is a little tricky to prevent collision with
3188 // the structure definition in the header. The rewriter has it's own
3189 // internal definition (__rw_objc_super) that is uses. This is why
3190 // we need the cast below. For example:
3191 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3192 //
3193 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3194 Context->getPointerType(SuperRep->getType()),
3195 VK_RValue, OK_Ordinary,
3196 SourceLocation());
3197 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3198 Context->getPointerType(superType),
3199 CK_BitCast, SuperRep);
3200 } else {
3201 // (struct objc_super) { <exprs from above> }
3202 InitListExpr *ILE =
3203 new (Context) InitListExpr(*Context, SourceLocation(),
3204 &InitExprs[0], InitExprs.size(),
3205 SourceLocation());
3206 TypeSourceInfo *superTInfo
3207 = Context->getTrivialTypeSourceInfo(superType);
3208 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3209 superType, VK_RValue, ILE,
3210 false);
3211 }
3212 MsgExprs.push_back(SuperRep);
3213 break;
3214 }
3215
3216 case ObjCMessageExpr::Instance: {
3217 // Remove all type-casts because it may contain objc-style types; e.g.
3218 // Foo<Proto> *.
3219 Expr *recExpr = Exp->getInstanceReceiver();
3220 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3221 recExpr = CE->getSubExpr();
3222 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3223 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3224 ? CK_BlockPointerToObjCPointerCast
3225 : CK_CPointerToObjCPointerCast;
3226
3227 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3228 CK, recExpr);
3229 MsgExprs.push_back(recExpr);
3230 break;
3231 }
3232 }
3233
3234 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3235 SmallVector<Expr*, 8> SelExprs;
3236 QualType argType = Context->getPointerType(Context->CharTy);
3237 SelExprs.push_back(StringLiteral::Create(*Context,
3238 Exp->getSelector().getAsString(),
3239 StringLiteral::Ascii, false,
3240 argType, SourceLocation()));
3241 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3242 &SelExprs[0], SelExprs.size(),
3243 StartLoc,
3244 EndLoc);
3245 MsgExprs.push_back(SelExp);
3246
3247 // Now push any user supplied arguments.
3248 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3249 Expr *userExpr = Exp->getArg(i);
3250 // Make all implicit casts explicit...ICE comes in handy:-)
3251 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3252 // Reuse the ICE type, it is exactly what the doctor ordered.
3253 QualType type = ICE->getType();
3254 if (needToScanForQualifiers(type))
3255 type = Context->getObjCIdType();
3256 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3257 (void)convertBlockPointerToFunctionPointer(type);
3258 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3259 CastKind CK;
3260 if (SubExpr->getType()->isIntegralType(*Context) &&
3261 type->isBooleanType()) {
3262 CK = CK_IntegralToBoolean;
3263 } else if (type->isObjCObjectPointerType()) {
3264 if (SubExpr->getType()->isBlockPointerType()) {
3265 CK = CK_BlockPointerToObjCPointerCast;
3266 } else if (SubExpr->getType()->isPointerType()) {
3267 CK = CK_CPointerToObjCPointerCast;
3268 } else {
3269 CK = CK_BitCast;
3270 }
3271 } else {
3272 CK = CK_BitCast;
3273 }
3274
3275 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3276 }
3277 // Make id<P...> cast into an 'id' cast.
3278 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3279 if (CE->getType()->isObjCQualifiedIdType()) {
3280 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3281 userExpr = CE->getSubExpr();
3282 CastKind CK;
3283 if (userExpr->getType()->isIntegralType(*Context)) {
3284 CK = CK_IntegralToPointer;
3285 } else if (userExpr->getType()->isBlockPointerType()) {
3286 CK = CK_BlockPointerToObjCPointerCast;
3287 } else if (userExpr->getType()->isPointerType()) {
3288 CK = CK_CPointerToObjCPointerCast;
3289 } else {
3290 CK = CK_BitCast;
3291 }
3292 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3293 CK, userExpr);
3294 }
3295 }
3296 MsgExprs.push_back(userExpr);
3297 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3298 // out the argument in the original expression (since we aren't deleting
3299 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3300 //Exp->setArg(i, 0);
3301 }
3302 // Generate the funky cast.
3303 CastExpr *cast;
3304 SmallVector<QualType, 8> ArgTypes;
3305 QualType returnType;
3306
3307 // Push 'id' and 'SEL', the 2 implicit arguments.
3308 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3309 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3310 else
3311 ArgTypes.push_back(Context->getObjCIdType());
3312 ArgTypes.push_back(Context->getObjCSelType());
3313 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3314 // Push any user argument types.
3315 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3316 E = OMD->param_end(); PI != E; ++PI) {
3317 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3318 ? Context->getObjCIdType()
3319 : (*PI)->getType();
3320 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3321 (void)convertBlockPointerToFunctionPointer(t);
3322 ArgTypes.push_back(t);
3323 }
3324 returnType = Exp->getType();
3325 convertToUnqualifiedObjCType(returnType);
3326 (void)convertBlockPointerToFunctionPointer(returnType);
3327 } else {
3328 returnType = Context->getObjCIdType();
3329 }
3330 // Get the type, we will need to reference it in a couple spots.
3331 QualType msgSendType = MsgSendFlavor->getType();
3332
3333 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003334 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003335 VK_LValue, SourceLocation());
3336
3337 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3338 // If we don't do this cast, we get the following bizarre warning/note:
3339 // xx.m:13: warning: function called through a non-compatible type
3340 // xx.m:13: note: if this code is reached, the program will abort
3341 cast = NoTypeInfoCStyleCastExpr(Context,
3342 Context->getPointerType(Context->VoidTy),
3343 CK_BitCast, DRE);
3344
3345 // Now do the "normal" pointer to function cast.
3346 QualType castType =
3347 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3348 // If we don't have a method decl, force a variadic cast.
3349 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3350 castType = Context->getPointerType(castType);
3351 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3352 cast);
3353
3354 // Don't forget the parens to enforce the proper binding.
3355 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3356
3357 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3358 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3359 MsgExprs.size(),
3360 FT->getResultType(), VK_RValue,
3361 EndLoc);
3362 Stmt *ReplacingStmt = CE;
3363 if (MsgSendStretFlavor) {
3364 // We have the method which returns a struct/union. Must also generate
3365 // call to objc_msgSend_stret and hang both varieties on a conditional
3366 // expression which dictate which one to envoke depending on size of
3367 // method's return type.
3368
3369 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003370 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3371 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003372 VK_LValue, SourceLocation());
3373 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3374 cast = NoTypeInfoCStyleCastExpr(Context,
3375 Context->getPointerType(Context->VoidTy),
3376 CK_BitCast, STDRE);
3377 // Now do the "normal" pointer to function cast.
3378 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3379 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3380 castType = Context->getPointerType(castType);
3381 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3382 cast);
3383
3384 // Don't forget the parens to enforce the proper binding.
3385 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3386
3387 FT = msgSendType->getAs<FunctionType>();
3388 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3389 MsgExprs.size(),
3390 FT->getResultType(), VK_RValue,
3391 SourceLocation());
3392
3393 // Build sizeof(returnType)
3394 UnaryExprOrTypeTraitExpr *sizeofExpr =
3395 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3396 Context->getTrivialTypeSourceInfo(returnType),
3397 Context->getSizeType(), SourceLocation(),
3398 SourceLocation());
3399 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3400 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3401 // For X86 it is more complicated and some kind of target specific routine
3402 // is needed to decide what to do.
3403 unsigned IntSize =
3404 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3405 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3406 llvm::APInt(IntSize, 8),
3407 Context->IntTy,
3408 SourceLocation());
3409 BinaryOperator *lessThanExpr =
3410 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3411 VK_RValue, OK_Ordinary, SourceLocation());
3412 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3413 ConditionalOperator *CondExpr =
3414 new (Context) ConditionalOperator(lessThanExpr,
3415 SourceLocation(), CE,
3416 SourceLocation(), STCE,
3417 returnType, VK_RValue, OK_Ordinary);
3418 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3419 CondExpr);
3420 }
3421 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3422 return ReplacingStmt;
3423}
3424
3425Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3426 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3427 Exp->getLocEnd());
3428
3429 // Now do the actual rewrite.
3430 ReplaceStmt(Exp, ReplacingStmt);
3431
3432 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3433 return ReplacingStmt;
3434}
3435
3436// typedef struct objc_object Protocol;
3437QualType RewriteModernObjC::getProtocolType() {
3438 if (!ProtocolTypeDecl) {
3439 TypeSourceInfo *TInfo
3440 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3441 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3442 SourceLocation(), SourceLocation(),
3443 &Context->Idents.get("Protocol"),
3444 TInfo);
3445 }
3446 return Context->getTypeDeclType(ProtocolTypeDecl);
3447}
3448
3449/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3450/// a synthesized/forward data reference (to the protocol's metadata).
3451/// The forward references (and metadata) are generated in
3452/// RewriteModernObjC::HandleTranslationUnit().
3453Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003454 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3455 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003456 IdentifierInfo *ID = &Context->Idents.get(Name);
3457 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3458 SourceLocation(), ID, getProtocolType(), 0,
3459 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003460 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3461 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003462 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3463 Context->getPointerType(DRE->getType()),
3464 VK_RValue, OK_Ordinary, SourceLocation());
3465 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3466 CK_BitCast,
3467 DerefExpr);
3468 ReplaceStmt(Exp, castExpr);
3469 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3470 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3471 return castExpr;
3472
3473}
3474
3475bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3476 const char *endBuf) {
3477 while (startBuf < endBuf) {
3478 if (*startBuf == '#') {
3479 // Skip whitespace.
3480 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3481 ;
3482 if (!strncmp(startBuf, "if", strlen("if")) ||
3483 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3484 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3485 !strncmp(startBuf, "define", strlen("define")) ||
3486 !strncmp(startBuf, "undef", strlen("undef")) ||
3487 !strncmp(startBuf, "else", strlen("else")) ||
3488 !strncmp(startBuf, "elif", strlen("elif")) ||
3489 !strncmp(startBuf, "endif", strlen("endif")) ||
3490 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3491 !strncmp(startBuf, "include", strlen("include")) ||
3492 !strncmp(startBuf, "import", strlen("import")) ||
3493 !strncmp(startBuf, "include_next", strlen("include_next")))
3494 return true;
3495 }
3496 startBuf++;
3497 }
3498 return false;
3499}
3500
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003501/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003502/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003503bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3504 std::string &Result) {
3505 if (Type->isArrayType()) {
3506 QualType ElemTy = Context->getBaseElementType(Type);
3507 return RewriteObjCFieldDeclType(ElemTy, Result);
3508 }
3509 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003510 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3511 if (RD->isCompleteDefinition()) {
3512 if (RD->isStruct())
3513 Result += "\n\tstruct ";
3514 else if (RD->isUnion())
3515 Result += "\n\tunion ";
3516 else
3517 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003518
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003519 Result += RD->getName();
3520 if (TagsDefinedInIvarDecls.count(RD)) {
3521 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003522 Result += " ";
3523 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003524 }
3525 TagsDefinedInIvarDecls.insert(RD);
3526 Result += " {\n";
3527 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003528 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003529 FieldDecl *FD = *i;
3530 RewriteObjCFieldDecl(FD, Result);
3531 }
3532 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003533 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003534 }
3535 }
3536 else if (Type->isEnumeralType()) {
3537 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3538 if (ED->isCompleteDefinition()) {
3539 Result += "\n\tenum ";
3540 Result += ED->getName();
3541 if (TagsDefinedInIvarDecls.count(ED)) {
3542 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003543 Result += " ";
3544 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003545 }
3546 TagsDefinedInIvarDecls.insert(ED);
3547
3548 Result += " {\n";
3549 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3550 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3551 Result += "\t"; Result += EC->getName(); Result += " = ";
3552 llvm::APSInt Val = EC->getInitVal();
3553 Result += Val.toString(10);
3554 Result += ",\n";
3555 }
3556 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003557 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003558 }
3559 }
3560
3561 Result += "\t";
3562 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003563 return false;
3564}
3565
3566
3567/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3568/// It handles elaborated types, as well as enum types in the process.
3569void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3570 std::string &Result) {
3571 QualType Type = fieldDecl->getType();
3572 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003573
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003574 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3575 if (!EleboratedType)
3576 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003577 Result += Name;
3578 if (fieldDecl->isBitField()) {
3579 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3580 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003581 else if (EleboratedType && Type->isArrayType()) {
3582 CanQualType CType = Context->getCanonicalType(Type);
3583 while (isa<ArrayType>(CType)) {
3584 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3585 Result += "[";
3586 llvm::APInt Dim = CAT->getSize();
3587 Result += utostr(Dim.getZExtValue());
3588 Result += "]";
3589 }
3590 CType = CType->getAs<ArrayType>()->getElementType();
3591 }
3592 }
3593
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003594 Result += ";\n";
3595}
3596
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003597/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3598/// an objective-c class with ivars.
3599void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3600 std::string &Result) {
3601 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3602 assert(CDecl->getName() != "" &&
3603 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003604 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003605 SmallVector<ObjCIvarDecl *, 8> IVars;
3606 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003607 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003608 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003609
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003610 SourceLocation LocStart = CDecl->getLocStart();
3611 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003612
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003613 const char *startBuf = SM->getCharacterData(LocStart);
3614 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003615
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003616 // If no ivars and no root or if its root, directly or indirectly,
3617 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003618 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003619 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3620 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3621 ReplaceText(LocStart, endBuf-startBuf, Result);
3622 return;
3623 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003624
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003625 Result += "\nstruct ";
3626 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003627 Result += "_IMPL {\n";
3628
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003629 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003630 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3631 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3632 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003633 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003634 TagsDefinedInIvarDecls.clear();
3635 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3636 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003637
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003638 Result += "};\n";
3639 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3640 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003641 // Mark this struct as having been generated.
3642 if (!ObjCSynthesizedStructs.insert(CDecl))
3643 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003644}
3645
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003646static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3647 ObjCIvarDecl *IvarDecl, std::string &Result) {
3648 Result += "OBJC_IVAR_$_";
3649 Result += IDecl->getName();
3650 Result += "$";
3651 Result += IvarDecl->getName();
3652}
3653
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003654/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3655/// have been referenced in an ivar access expression.
3656void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3657 std::string &Result) {
3658 // write out ivar offset symbols which have been referenced in an ivar
3659 // access expression.
3660 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3661 if (Ivars.empty())
3662 return;
3663 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3664 e = Ivars.end(); i != e; i++) {
3665 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003666 Result += "\n";
3667 if (LangOpts.MicrosoftExt)
3668 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003669 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003670 if (LangOpts.MicrosoftExt &&
3671 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003672 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3673 Result += "__declspec(dllimport) ";
3674
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003675 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003676 WriteInternalIvarName(CDecl, IvarDecl, Result);
3677 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003678 }
3679}
3680
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003681//===----------------------------------------------------------------------===//
3682// Meta Data Emission
3683//===----------------------------------------------------------------------===//
3684
3685
3686/// RewriteImplementations - This routine rewrites all method implementations
3687/// and emits meta-data.
3688
3689void RewriteModernObjC::RewriteImplementations() {
3690 int ClsDefCount = ClassImplementation.size();
3691 int CatDefCount = CategoryImplementation.size();
3692
3693 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003694 for (int i = 0; i < ClsDefCount; i++) {
3695 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3696 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3697 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003698 assert(false &&
3699 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003700 RewriteImplementationDecl(OIMP);
3701 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003702
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003703 for (int i = 0; i < CatDefCount; i++) {
3704 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3705 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3706 if (CDecl->isImplicitInterfaceDecl())
3707 assert(false &&
3708 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003709 RewriteImplementationDecl(CIMP);
3710 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003711}
3712
3713void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3714 const std::string &Name,
3715 ValueDecl *VD, bool def) {
3716 assert(BlockByRefDeclNo.count(VD) &&
3717 "RewriteByRefString: ByRef decl missing");
3718 if (def)
3719 ResultStr += "struct ";
3720 ResultStr += "__Block_byref_" + Name +
3721 "_" + utostr(BlockByRefDeclNo[VD]) ;
3722}
3723
3724static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3725 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3726 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3727 return false;
3728}
3729
3730std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3731 StringRef funcName,
3732 std::string Tag) {
3733 const FunctionType *AFT = CE->getFunctionType();
3734 QualType RT = AFT->getResultType();
3735 std::string StructRef = "struct " + Tag;
3736 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003737 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003738
3739 BlockDecl *BD = CE->getBlockDecl();
3740
3741 if (isa<FunctionNoProtoType>(AFT)) {
3742 // No user-supplied arguments. Still need to pass in a pointer to the
3743 // block (to reference imported block decl refs).
3744 S += "(" + StructRef + " *__cself)";
3745 } else if (BD->param_empty()) {
3746 S += "(" + StructRef + " *__cself)";
3747 } else {
3748 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3749 assert(FT && "SynthesizeBlockFunc: No function proto");
3750 S += '(';
3751 // first add the implicit argument.
3752 S += StructRef + " *__cself, ";
3753 std::string ParamStr;
3754 for (BlockDecl::param_iterator AI = BD->param_begin(),
3755 E = BD->param_end(); AI != E; ++AI) {
3756 if (AI != BD->param_begin()) S += ", ";
3757 ParamStr = (*AI)->getNameAsString();
3758 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003759 (void)convertBlockPointerToFunctionPointer(QT);
3760 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003761 S += ParamStr;
3762 }
3763 if (FT->isVariadic()) {
3764 if (!BD->param_empty()) S += ", ";
3765 S += "...";
3766 }
3767 S += ')';
3768 }
3769 S += " {\n";
3770
3771 // Create local declarations to avoid rewriting all closure decl ref exprs.
3772 // First, emit a declaration for all "by ref" decls.
3773 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3774 E = BlockByRefDecls.end(); I != E; ++I) {
3775 S += " ";
3776 std::string Name = (*I)->getNameAsString();
3777 std::string TypeString;
3778 RewriteByRefString(TypeString, Name, (*I));
3779 TypeString += " *";
3780 Name = TypeString + Name;
3781 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3782 }
3783 // Next, emit a declaration for all "by copy" declarations.
3784 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3785 E = BlockByCopyDecls.end(); I != E; ++I) {
3786 S += " ";
3787 // Handle nested closure invocation. For example:
3788 //
3789 // void (^myImportedClosure)(void);
3790 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3791 //
3792 // void (^anotherClosure)(void);
3793 // anotherClosure = ^(void) {
3794 // myImportedClosure(); // import and invoke the closure
3795 // };
3796 //
3797 if (isTopLevelBlockPointerType((*I)->getType())) {
3798 RewriteBlockPointerTypeVariable(S, (*I));
3799 S += " = (";
3800 RewriteBlockPointerType(S, (*I)->getType());
3801 S += ")";
3802 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3803 }
3804 else {
3805 std::string Name = (*I)->getNameAsString();
3806 QualType QT = (*I)->getType();
3807 if (HasLocalVariableExternalStorage(*I))
3808 QT = Context->getPointerType(QT);
3809 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3810 S += Name + " = __cself->" +
3811 (*I)->getNameAsString() + "; // bound by copy\n";
3812 }
3813 }
3814 std::string RewrittenStr = RewrittenBlockExprs[CE];
3815 const char *cstr = RewrittenStr.c_str();
3816 while (*cstr++ != '{') ;
3817 S += cstr;
3818 S += "\n";
3819 return S;
3820}
3821
3822std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3823 StringRef funcName,
3824 std::string Tag) {
3825 std::string StructRef = "struct " + Tag;
3826 std::string S = "static void __";
3827
3828 S += funcName;
3829 S += "_block_copy_" + utostr(i);
3830 S += "(" + StructRef;
3831 S += "*dst, " + StructRef;
3832 S += "*src) {";
3833 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3834 E = ImportedBlockDecls.end(); I != E; ++I) {
3835 ValueDecl *VD = (*I);
3836 S += "_Block_object_assign((void*)&dst->";
3837 S += (*I)->getNameAsString();
3838 S += ", (void*)src->";
3839 S += (*I)->getNameAsString();
3840 if (BlockByRefDeclsPtrSet.count((*I)))
3841 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3842 else if (VD->getType()->isBlockPointerType())
3843 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3844 else
3845 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3846 }
3847 S += "}\n";
3848
3849 S += "\nstatic void __";
3850 S += funcName;
3851 S += "_block_dispose_" + utostr(i);
3852 S += "(" + StructRef;
3853 S += "*src) {";
3854 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3855 E = ImportedBlockDecls.end(); I != E; ++I) {
3856 ValueDecl *VD = (*I);
3857 S += "_Block_object_dispose((void*)src->";
3858 S += (*I)->getNameAsString();
3859 if (BlockByRefDeclsPtrSet.count((*I)))
3860 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3861 else if (VD->getType()->isBlockPointerType())
3862 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3863 else
3864 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3865 }
3866 S += "}\n";
3867 return S;
3868}
3869
3870std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3871 std::string Desc) {
3872 std::string S = "\nstruct " + Tag;
3873 std::string Constructor = " " + Tag;
3874
3875 S += " {\n struct __block_impl impl;\n";
3876 S += " struct " + Desc;
3877 S += "* Desc;\n";
3878
3879 Constructor += "(void *fp, "; // Invoke function pointer.
3880 Constructor += "struct " + Desc; // Descriptor pointer.
3881 Constructor += " *desc";
3882
3883 if (BlockDeclRefs.size()) {
3884 // Output all "by copy" declarations.
3885 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3886 E = BlockByCopyDecls.end(); I != E; ++I) {
3887 S += " ";
3888 std::string FieldName = (*I)->getNameAsString();
3889 std::string ArgName = "_" + FieldName;
3890 // Handle nested closure invocation. For example:
3891 //
3892 // void (^myImportedBlock)(void);
3893 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3894 //
3895 // void (^anotherBlock)(void);
3896 // anotherBlock = ^(void) {
3897 // myImportedBlock(); // import and invoke the closure
3898 // };
3899 //
3900 if (isTopLevelBlockPointerType((*I)->getType())) {
3901 S += "struct __block_impl *";
3902 Constructor += ", void *" + ArgName;
3903 } else {
3904 QualType QT = (*I)->getType();
3905 if (HasLocalVariableExternalStorage(*I))
3906 QT = Context->getPointerType(QT);
3907 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3908 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3909 Constructor += ", " + ArgName;
3910 }
3911 S += FieldName + ";\n";
3912 }
3913 // Output all "by ref" declarations.
3914 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3915 E = BlockByRefDecls.end(); I != E; ++I) {
3916 S += " ";
3917 std::string FieldName = (*I)->getNameAsString();
3918 std::string ArgName = "_" + FieldName;
3919 {
3920 std::string TypeString;
3921 RewriteByRefString(TypeString, FieldName, (*I));
3922 TypeString += " *";
3923 FieldName = TypeString + FieldName;
3924 ArgName = TypeString + ArgName;
3925 Constructor += ", " + ArgName;
3926 }
3927 S += FieldName + "; // by ref\n";
3928 }
3929 // Finish writing the constructor.
3930 Constructor += ", int flags=0)";
3931 // Initialize all "by copy" arguments.
3932 bool firsTime = true;
3933 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3934 E = BlockByCopyDecls.end(); I != E; ++I) {
3935 std::string Name = (*I)->getNameAsString();
3936 if (firsTime) {
3937 Constructor += " : ";
3938 firsTime = false;
3939 }
3940 else
3941 Constructor += ", ";
3942 if (isTopLevelBlockPointerType((*I)->getType()))
3943 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3944 else
3945 Constructor += Name + "(_" + Name + ")";
3946 }
3947 // Initialize all "by ref" arguments.
3948 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3949 E = BlockByRefDecls.end(); I != E; ++I) {
3950 std::string Name = (*I)->getNameAsString();
3951 if (firsTime) {
3952 Constructor += " : ";
3953 firsTime = false;
3954 }
3955 else
3956 Constructor += ", ";
3957 Constructor += Name + "(_" + Name + "->__forwarding)";
3958 }
3959
3960 Constructor += " {\n";
3961 if (GlobalVarDecl)
3962 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3963 else
3964 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3965 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3966
3967 Constructor += " Desc = desc;\n";
3968 } else {
3969 // Finish writing the constructor.
3970 Constructor += ", int flags=0) {\n";
3971 if (GlobalVarDecl)
3972 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3973 else
3974 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3975 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3976 Constructor += " Desc = desc;\n";
3977 }
3978 Constructor += " ";
3979 Constructor += "}\n";
3980 S += Constructor;
3981 S += "};\n";
3982 return S;
3983}
3984
3985std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3986 std::string ImplTag, int i,
3987 StringRef FunName,
3988 unsigned hasCopy) {
3989 std::string S = "\nstatic struct " + DescTag;
3990
3991 S += " {\n unsigned long reserved;\n";
3992 S += " unsigned long Block_size;\n";
3993 if (hasCopy) {
3994 S += " void (*copy)(struct ";
3995 S += ImplTag; S += "*, struct ";
3996 S += ImplTag; S += "*);\n";
3997
3998 S += " void (*dispose)(struct ";
3999 S += ImplTag; S += "*);\n";
4000 }
4001 S += "} ";
4002
4003 S += DescTag + "_DATA = { 0, sizeof(struct ";
4004 S += ImplTag + ")";
4005 if (hasCopy) {
4006 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4007 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4008 }
4009 S += "};\n";
4010 return S;
4011}
4012
4013void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4014 StringRef FunName) {
4015 // Insert declaration for the function in which block literal is used.
4016 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
4017 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4018 bool RewriteSC = (GlobalVarDecl &&
4019 !Blocks.empty() &&
4020 GlobalVarDecl->getStorageClass() == SC_Static &&
4021 GlobalVarDecl->getType().getCVRQualifiers());
4022 if (RewriteSC) {
4023 std::string SC(" void __");
4024 SC += GlobalVarDecl->getNameAsString();
4025 SC += "() {}";
4026 InsertText(FunLocStart, SC);
4027 }
4028
4029 // Insert closures that were part of the function.
4030 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4031 CollectBlockDeclRefInfo(Blocks[i]);
4032 // Need to copy-in the inner copied-in variables not actually used in this
4033 // block.
4034 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004035 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004036 ValueDecl *VD = Exp->getDecl();
4037 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004038 if (!VD->hasAttr<BlocksAttr>()) {
4039 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4040 BlockByCopyDeclsPtrSet.insert(VD);
4041 BlockByCopyDecls.push_back(VD);
4042 }
4043 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004044 }
John McCallf4b88a42012-03-10 09:33:50 +00004045
4046 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004047 BlockByRefDeclsPtrSet.insert(VD);
4048 BlockByRefDecls.push_back(VD);
4049 }
John McCallf4b88a42012-03-10 09:33:50 +00004050
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004051 // imported objects in the inner blocks not used in the outer
4052 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004053 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004054 VD->getType()->isBlockPointerType())
4055 ImportedBlockDecls.insert(VD);
4056 }
4057
4058 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4059 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4060
4061 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4062
4063 InsertText(FunLocStart, CI);
4064
4065 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4066
4067 InsertText(FunLocStart, CF);
4068
4069 if (ImportedBlockDecls.size()) {
4070 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4071 InsertText(FunLocStart, HF);
4072 }
4073 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4074 ImportedBlockDecls.size() > 0);
4075 InsertText(FunLocStart, BD);
4076
4077 BlockDeclRefs.clear();
4078 BlockByRefDecls.clear();
4079 BlockByRefDeclsPtrSet.clear();
4080 BlockByCopyDecls.clear();
4081 BlockByCopyDeclsPtrSet.clear();
4082 ImportedBlockDecls.clear();
4083 }
4084 if (RewriteSC) {
4085 // Must insert any 'const/volatile/static here. Since it has been
4086 // removed as result of rewriting of block literals.
4087 std::string SC;
4088 if (GlobalVarDecl->getStorageClass() == SC_Static)
4089 SC = "static ";
4090 if (GlobalVarDecl->getType().isConstQualified())
4091 SC += "const ";
4092 if (GlobalVarDecl->getType().isVolatileQualified())
4093 SC += "volatile ";
4094 if (GlobalVarDecl->getType().isRestrictQualified())
4095 SC += "restrict ";
4096 InsertText(FunLocStart, SC);
4097 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004098 if (GlobalConstructionExp) {
4099 // extra fancy dance for global literal expression.
4100
4101 // Always the latest block expression on the block stack.
4102 std::string Tag = "__";
4103 Tag += FunName;
4104 Tag += "_block_impl_";
4105 Tag += utostr(Blocks.size()-1);
4106 std::string globalBuf = "static ";
4107 globalBuf += Tag; globalBuf += " ";
4108 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004109
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004110 llvm::raw_string_ostream constructorExprBuf(SStr);
4111 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4112 PrintingPolicy(LangOpts));
4113 globalBuf += constructorExprBuf.str();
4114 globalBuf += ";\n";
4115 InsertText(FunLocStart, globalBuf);
4116 GlobalConstructionExp = 0;
4117 }
4118
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004119 Blocks.clear();
4120 InnerDeclRefsCount.clear();
4121 InnerDeclRefs.clear();
4122 RewrittenBlockExprs.clear();
4123}
4124
4125void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4126 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
4127 StringRef FuncName = FD->getName();
4128
4129 SynthesizeBlockLiterals(FunLocStart, FuncName);
4130}
4131
4132static void BuildUniqueMethodName(std::string &Name,
4133 ObjCMethodDecl *MD) {
4134 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4135 Name = IFace->getName();
4136 Name += "__" + MD->getSelector().getAsString();
4137 // Convert colons to underscores.
4138 std::string::size_type loc = 0;
4139 while ((loc = Name.find(":", loc)) != std::string::npos)
4140 Name.replace(loc, 1, "_");
4141}
4142
4143void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4144 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4145 //SourceLocation FunLocStart = MD->getLocStart();
4146 SourceLocation FunLocStart = MD->getLocStart();
4147 std::string FuncName;
4148 BuildUniqueMethodName(FuncName, MD);
4149 SynthesizeBlockLiterals(FunLocStart, FuncName);
4150}
4151
4152void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4153 for (Stmt::child_range CI = S->children(); CI; ++CI)
4154 if (*CI) {
4155 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4156 GetBlockDeclRefExprs(CBE->getBody());
4157 else
4158 GetBlockDeclRefExprs(*CI);
4159 }
4160 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004161 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4162 if (DRE->refersToEnclosingLocal() &&
4163 HasLocalVariableExternalStorage(DRE->getDecl())) {
4164 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004165 }
4166
4167 return;
4168}
4169
4170void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004171 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004172 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4173 for (Stmt::child_range CI = S->children(); CI; ++CI)
4174 if (*CI) {
4175 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4176 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4177 GetInnerBlockDeclRefExprs(CBE->getBody(),
4178 InnerBlockDeclRefs,
4179 InnerContexts);
4180 }
4181 else
4182 GetInnerBlockDeclRefExprs(*CI,
4183 InnerBlockDeclRefs,
4184 InnerContexts);
4185
4186 }
4187 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004188 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4189 if (DRE->refersToEnclosingLocal()) {
4190 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4191 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4192 InnerBlockDeclRefs.push_back(DRE);
4193 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4194 if (Var->isFunctionOrMethodVarDecl())
4195 ImportedLocalExternalDecls.insert(Var);
4196 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004197 }
4198
4199 return;
4200}
4201
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004202/// convertObjCTypeToCStyleType - This routine converts such objc types
4203/// as qualified objects, and blocks to their closest c/c++ types that
4204/// it can. It returns true if input type was modified.
4205bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4206 QualType oldT = T;
4207 convertBlockPointerToFunctionPointer(T);
4208 if (T->isFunctionPointerType()) {
4209 QualType PointeeTy;
4210 if (const PointerType* PT = T->getAs<PointerType>()) {
4211 PointeeTy = PT->getPointeeType();
4212 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4213 T = convertFunctionTypeOfBlocks(FT);
4214 T = Context->getPointerType(T);
4215 }
4216 }
4217 }
4218
4219 convertToUnqualifiedObjCType(T);
4220 return T != oldT;
4221}
4222
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004223/// convertFunctionTypeOfBlocks - This routine converts a function type
4224/// whose result type may be a block pointer or whose argument type(s)
4225/// might be block pointers to an equivalent function type replacing
4226/// all block pointers to function pointers.
4227QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4228 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4229 // FTP will be null for closures that don't take arguments.
4230 // Generate a funky cast.
4231 SmallVector<QualType, 8> ArgTypes;
4232 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004233 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004234
4235 if (FTP) {
4236 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4237 E = FTP->arg_type_end(); I && (I != E); ++I) {
4238 QualType t = *I;
4239 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004240 if (convertObjCTypeToCStyleType(t))
4241 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004242 ArgTypes.push_back(t);
4243 }
4244 }
4245 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004246 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004247 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4248 else FuncType = QualType(FT, 0);
4249 return FuncType;
4250}
4251
4252Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4253 // Navigate to relevant type information.
4254 const BlockPointerType *CPT = 0;
4255
4256 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4257 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004258 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4259 CPT = MExpr->getType()->getAs<BlockPointerType>();
4260 }
4261 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4262 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4263 }
4264 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4265 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4266 else if (const ConditionalOperator *CEXPR =
4267 dyn_cast<ConditionalOperator>(BlockExp)) {
4268 Expr *LHSExp = CEXPR->getLHS();
4269 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4270 Expr *RHSExp = CEXPR->getRHS();
4271 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4272 Expr *CONDExp = CEXPR->getCond();
4273 ConditionalOperator *CondExpr =
4274 new (Context) ConditionalOperator(CONDExp,
4275 SourceLocation(), cast<Expr>(LHSStmt),
4276 SourceLocation(), cast<Expr>(RHSStmt),
4277 Exp->getType(), VK_RValue, OK_Ordinary);
4278 return CondExpr;
4279 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4280 CPT = IRE->getType()->getAs<BlockPointerType>();
4281 } else if (const PseudoObjectExpr *POE
4282 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4283 CPT = POE->getType()->castAs<BlockPointerType>();
4284 } else {
4285 assert(1 && "RewriteBlockClass: Bad type");
4286 }
4287 assert(CPT && "RewriteBlockClass: Bad type");
4288 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4289 assert(FT && "RewriteBlockClass: Bad type");
4290 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4291 // FTP will be null for closures that don't take arguments.
4292
4293 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4294 SourceLocation(), SourceLocation(),
4295 &Context->Idents.get("__block_impl"));
4296 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4297
4298 // Generate a funky cast.
4299 SmallVector<QualType, 8> ArgTypes;
4300
4301 // Push the block argument type.
4302 ArgTypes.push_back(PtrBlock);
4303 if (FTP) {
4304 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4305 E = FTP->arg_type_end(); I && (I != E); ++I) {
4306 QualType t = *I;
4307 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4308 if (!convertBlockPointerToFunctionPointer(t))
4309 convertToUnqualifiedObjCType(t);
4310 ArgTypes.push_back(t);
4311 }
4312 }
4313 // Now do the pointer to function cast.
4314 QualType PtrToFuncCastType
4315 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4316
4317 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4318
4319 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4320 CK_BitCast,
4321 const_cast<Expr*>(BlockExp));
4322 // Don't forget the parens to enforce the proper binding.
4323 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4324 BlkCast);
4325 //PE->dump();
4326
4327 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4328 SourceLocation(),
4329 &Context->Idents.get("FuncPtr"),
4330 Context->VoidPtrTy, 0,
4331 /*BitWidth=*/0, /*Mutable=*/true,
4332 /*HasInit=*/false);
4333 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4334 FD->getType(), VK_LValue,
4335 OK_Ordinary);
4336
4337
4338 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4339 CK_BitCast, ME);
4340 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4341
4342 SmallVector<Expr*, 8> BlkExprs;
4343 // Add the implicit argument.
4344 BlkExprs.push_back(BlkCast);
4345 // Add the user arguments.
4346 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4347 E = Exp->arg_end(); I != E; ++I) {
4348 BlkExprs.push_back(*I);
4349 }
4350 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4351 BlkExprs.size(),
4352 Exp->getType(), VK_RValue,
4353 SourceLocation());
4354 return CE;
4355}
4356
4357// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004358// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004359// For example:
4360//
4361// int main() {
4362// __block Foo *f;
4363// __block int i;
4364//
4365// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004366// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004367// i = 77;
4368// };
4369//}
John McCallf4b88a42012-03-10 09:33:50 +00004370Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004371 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4372 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004373 ValueDecl *VD = DeclRefExp->getDecl();
4374 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004375
4376 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4377 SourceLocation(),
4378 &Context->Idents.get("__forwarding"),
4379 Context->VoidPtrTy, 0,
4380 /*BitWidth=*/0, /*Mutable=*/true,
4381 /*HasInit=*/false);
4382 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4383 FD, SourceLocation(),
4384 FD->getType(), VK_LValue,
4385 OK_Ordinary);
4386
4387 StringRef Name = VD->getName();
4388 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4389 &Context->Idents.get(Name),
4390 Context->VoidPtrTy, 0,
4391 /*BitWidth=*/0, /*Mutable=*/true,
4392 /*HasInit=*/false);
4393 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4394 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4395
4396
4397
4398 // Need parens to enforce precedence.
4399 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4400 DeclRefExp->getExprLoc(),
4401 ME);
4402 ReplaceStmt(DeclRefExp, PE);
4403 return PE;
4404}
4405
4406// Rewrites the imported local variable V with external storage
4407// (static, extern, etc.) as *V
4408//
4409Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4410 ValueDecl *VD = DRE->getDecl();
4411 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4412 if (!ImportedLocalExternalDecls.count(Var))
4413 return DRE;
4414 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4415 VK_LValue, OK_Ordinary,
4416 DRE->getLocation());
4417 // Need parens to enforce precedence.
4418 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4419 Exp);
4420 ReplaceStmt(DRE, PE);
4421 return PE;
4422}
4423
4424void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4425 SourceLocation LocStart = CE->getLParenLoc();
4426 SourceLocation LocEnd = CE->getRParenLoc();
4427
4428 // Need to avoid trying to rewrite synthesized casts.
4429 if (LocStart.isInvalid())
4430 return;
4431 // Need to avoid trying to rewrite casts contained in macros.
4432 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4433 return;
4434
4435 const char *startBuf = SM->getCharacterData(LocStart);
4436 const char *endBuf = SM->getCharacterData(LocEnd);
4437 QualType QT = CE->getType();
4438 const Type* TypePtr = QT->getAs<Type>();
4439 if (isa<TypeOfExprType>(TypePtr)) {
4440 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4441 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4442 std::string TypeAsString = "(";
4443 RewriteBlockPointerType(TypeAsString, QT);
4444 TypeAsString += ")";
4445 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4446 return;
4447 }
4448 // advance the location to startArgList.
4449 const char *argPtr = startBuf;
4450
4451 while (*argPtr++ && (argPtr < endBuf)) {
4452 switch (*argPtr) {
4453 case '^':
4454 // Replace the '^' with '*'.
4455 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4456 ReplaceText(LocStart, 1, "*");
4457 break;
4458 }
4459 }
4460 return;
4461}
4462
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004463void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4464 CastKind CastKind = IC->getCastKind();
4465
4466 if (CastKind == CK_BlockPointerToObjCPointerCast) {
4467 CStyleCastExpr * CastExpr =
4468 NoTypeInfoCStyleCastExpr(Context, IC->getType(), CK_BitCast, IC);
4469 ReplaceStmt(IC, CastExpr);
4470 }
4471 else if (CastKind == CK_AnyPointerToBlockPointerCast) {
4472 QualType BlockT = IC->getType();
4473 (void)convertBlockPointerToFunctionPointer(BlockT);
4474 CStyleCastExpr * CastExpr =
4475 NoTypeInfoCStyleCastExpr(Context, BlockT, CK_BitCast, IC);
4476 ReplaceStmt(IC, CastExpr);
4477 }
4478 return;
4479}
4480
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004481void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4482 SourceLocation DeclLoc = FD->getLocation();
4483 unsigned parenCount = 0;
4484
4485 // We have 1 or more arguments that have closure pointers.
4486 const char *startBuf = SM->getCharacterData(DeclLoc);
4487 const char *startArgList = strchr(startBuf, '(');
4488
4489 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4490
4491 parenCount++;
4492 // advance the location to startArgList.
4493 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4494 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4495
4496 const char *argPtr = startArgList;
4497
4498 while (*argPtr++ && parenCount) {
4499 switch (*argPtr) {
4500 case '^':
4501 // Replace the '^' with '*'.
4502 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4503 ReplaceText(DeclLoc, 1, "*");
4504 break;
4505 case '(':
4506 parenCount++;
4507 break;
4508 case ')':
4509 parenCount--;
4510 break;
4511 }
4512 }
4513 return;
4514}
4515
4516bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4517 const FunctionProtoType *FTP;
4518 const PointerType *PT = QT->getAs<PointerType>();
4519 if (PT) {
4520 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4521 } else {
4522 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4523 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4524 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4525 }
4526 if (FTP) {
4527 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4528 E = FTP->arg_type_end(); I != E; ++I)
4529 if (isTopLevelBlockPointerType(*I))
4530 return true;
4531 }
4532 return false;
4533}
4534
4535bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4536 const FunctionProtoType *FTP;
4537 const PointerType *PT = QT->getAs<PointerType>();
4538 if (PT) {
4539 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4540 } else {
4541 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4542 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4543 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4544 }
4545 if (FTP) {
4546 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4547 E = FTP->arg_type_end(); I != E; ++I) {
4548 if ((*I)->isObjCQualifiedIdType())
4549 return true;
4550 if ((*I)->isObjCObjectPointerType() &&
4551 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4552 return true;
4553 }
4554
4555 }
4556 return false;
4557}
4558
4559void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4560 const char *&RParen) {
4561 const char *argPtr = strchr(Name, '(');
4562 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4563
4564 LParen = argPtr; // output the start.
4565 argPtr++; // skip past the left paren.
4566 unsigned parenCount = 1;
4567
4568 while (*argPtr && parenCount) {
4569 switch (*argPtr) {
4570 case '(': parenCount++; break;
4571 case ')': parenCount--; break;
4572 default: break;
4573 }
4574 if (parenCount) argPtr++;
4575 }
4576 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4577 RParen = argPtr; // output the end
4578}
4579
4580void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4581 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4582 RewriteBlockPointerFunctionArgs(FD);
4583 return;
4584 }
4585 // Handle Variables and Typedefs.
4586 SourceLocation DeclLoc = ND->getLocation();
4587 QualType DeclT;
4588 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4589 DeclT = VD->getType();
4590 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4591 DeclT = TDD->getUnderlyingType();
4592 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4593 DeclT = FD->getType();
4594 else
4595 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4596
4597 const char *startBuf = SM->getCharacterData(DeclLoc);
4598 const char *endBuf = startBuf;
4599 // scan backward (from the decl location) for the end of the previous decl.
4600 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4601 startBuf--;
4602 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4603 std::string buf;
4604 unsigned OrigLength=0;
4605 // *startBuf != '^' if we are dealing with a pointer to function that
4606 // may take block argument types (which will be handled below).
4607 if (*startBuf == '^') {
4608 // Replace the '^' with '*', computing a negative offset.
4609 buf = '*';
4610 startBuf++;
4611 OrigLength++;
4612 }
4613 while (*startBuf != ')') {
4614 buf += *startBuf;
4615 startBuf++;
4616 OrigLength++;
4617 }
4618 buf += ')';
4619 OrigLength++;
4620
4621 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4622 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4623 // Replace the '^' with '*' for arguments.
4624 // Replace id<P> with id/*<>*/
4625 DeclLoc = ND->getLocation();
4626 startBuf = SM->getCharacterData(DeclLoc);
4627 const char *argListBegin, *argListEnd;
4628 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4629 while (argListBegin < argListEnd) {
4630 if (*argListBegin == '^')
4631 buf += '*';
4632 else if (*argListBegin == '<') {
4633 buf += "/*";
4634 buf += *argListBegin++;
4635 OrigLength++;;
4636 while (*argListBegin != '>') {
4637 buf += *argListBegin++;
4638 OrigLength++;
4639 }
4640 buf += *argListBegin;
4641 buf += "*/";
4642 }
4643 else
4644 buf += *argListBegin;
4645 argListBegin++;
4646 OrigLength++;
4647 }
4648 buf += ')';
4649 OrigLength++;
4650 }
4651 ReplaceText(Start, OrigLength, buf);
4652
4653 return;
4654}
4655
4656
4657/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4658/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4659/// struct Block_byref_id_object *src) {
4660/// _Block_object_assign (&_dest->object, _src->object,
4661/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4662/// [|BLOCK_FIELD_IS_WEAK]) // object
4663/// _Block_object_assign(&_dest->object, _src->object,
4664/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4665/// [|BLOCK_FIELD_IS_WEAK]) // block
4666/// }
4667/// And:
4668/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4669/// _Block_object_dispose(_src->object,
4670/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4671/// [|BLOCK_FIELD_IS_WEAK]) // object
4672/// _Block_object_dispose(_src->object,
4673/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4674/// [|BLOCK_FIELD_IS_WEAK]) // block
4675/// }
4676
4677std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4678 int flag) {
4679 std::string S;
4680 if (CopyDestroyCache.count(flag))
4681 return S;
4682 CopyDestroyCache.insert(flag);
4683 S = "static void __Block_byref_id_object_copy_";
4684 S += utostr(flag);
4685 S += "(void *dst, void *src) {\n";
4686
4687 // offset into the object pointer is computed as:
4688 // void * + void* + int + int + void* + void *
4689 unsigned IntSize =
4690 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4691 unsigned VoidPtrSize =
4692 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4693
4694 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4695 S += " _Block_object_assign((char*)dst + ";
4696 S += utostr(offset);
4697 S += ", *(void * *) ((char*)src + ";
4698 S += utostr(offset);
4699 S += "), ";
4700 S += utostr(flag);
4701 S += ");\n}\n";
4702
4703 S += "static void __Block_byref_id_object_dispose_";
4704 S += utostr(flag);
4705 S += "(void *src) {\n";
4706 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4707 S += utostr(offset);
4708 S += "), ";
4709 S += utostr(flag);
4710 S += ");\n}\n";
4711 return S;
4712}
4713
4714/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4715/// the declaration into:
4716/// struct __Block_byref_ND {
4717/// void *__isa; // NULL for everything except __weak pointers
4718/// struct __Block_byref_ND *__forwarding;
4719/// int32_t __flags;
4720/// int32_t __size;
4721/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4722/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4723/// typex ND;
4724/// };
4725///
4726/// It then replaces declaration of ND variable with:
4727/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4728/// __size=sizeof(struct __Block_byref_ND),
4729/// ND=initializer-if-any};
4730///
4731///
4732void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4733 // Insert declaration for the function in which block literal is
4734 // used.
4735 if (CurFunctionDeclToDeclareForBlock)
4736 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4737 int flag = 0;
4738 int isa = 0;
4739 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4740 if (DeclLoc.isInvalid())
4741 // If type location is missing, it is because of missing type (a warning).
4742 // Use variable's location which is good for this case.
4743 DeclLoc = ND->getLocation();
4744 const char *startBuf = SM->getCharacterData(DeclLoc);
4745 SourceLocation X = ND->getLocEnd();
4746 X = SM->getExpansionLoc(X);
4747 const char *endBuf = SM->getCharacterData(X);
4748 std::string Name(ND->getNameAsString());
4749 std::string ByrefType;
4750 RewriteByRefString(ByrefType, Name, ND, true);
4751 ByrefType += " {\n";
4752 ByrefType += " void *__isa;\n";
4753 RewriteByRefString(ByrefType, Name, ND);
4754 ByrefType += " *__forwarding;\n";
4755 ByrefType += " int __flags;\n";
4756 ByrefType += " int __size;\n";
4757 // Add void *__Block_byref_id_object_copy;
4758 // void *__Block_byref_id_object_dispose; if needed.
4759 QualType Ty = ND->getType();
4760 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4761 if (HasCopyAndDispose) {
4762 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4763 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4764 }
4765
4766 QualType T = Ty;
4767 (void)convertBlockPointerToFunctionPointer(T);
4768 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4769
4770 ByrefType += " " + Name + ";\n";
4771 ByrefType += "};\n";
4772 // Insert this type in global scope. It is needed by helper function.
4773 SourceLocation FunLocStart;
4774 if (CurFunctionDef)
4775 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4776 else {
4777 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4778 FunLocStart = CurMethodDef->getLocStart();
4779 }
4780 InsertText(FunLocStart, ByrefType);
4781 if (Ty.isObjCGCWeak()) {
4782 flag |= BLOCK_FIELD_IS_WEAK;
4783 isa = 1;
4784 }
4785
4786 if (HasCopyAndDispose) {
4787 flag = BLOCK_BYREF_CALLER;
4788 QualType Ty = ND->getType();
4789 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4790 if (Ty->isBlockPointerType())
4791 flag |= BLOCK_FIELD_IS_BLOCK;
4792 else
4793 flag |= BLOCK_FIELD_IS_OBJECT;
4794 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4795 if (!HF.empty())
4796 InsertText(FunLocStart, HF);
4797 }
4798
4799 // struct __Block_byref_ND ND =
4800 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4801 // initializer-if-any};
4802 bool hasInit = (ND->getInit() != 0);
4803 unsigned flags = 0;
4804 if (HasCopyAndDispose)
4805 flags |= BLOCK_HAS_COPY_DISPOSE;
4806 Name = ND->getNameAsString();
4807 ByrefType.clear();
4808 RewriteByRefString(ByrefType, Name, ND);
4809 std::string ForwardingCastType("(");
4810 ForwardingCastType += ByrefType + " *)";
4811 if (!hasInit) {
4812 ByrefType += " " + Name + " = {(void*)";
4813 ByrefType += utostr(isa);
4814 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4815 ByrefType += utostr(flags);
4816 ByrefType += ", ";
4817 ByrefType += "sizeof(";
4818 RewriteByRefString(ByrefType, Name, ND);
4819 ByrefType += ")";
4820 if (HasCopyAndDispose) {
4821 ByrefType += ", __Block_byref_id_object_copy_";
4822 ByrefType += utostr(flag);
4823 ByrefType += ", __Block_byref_id_object_dispose_";
4824 ByrefType += utostr(flag);
4825 }
4826 ByrefType += "};\n";
4827 unsigned nameSize = Name.size();
4828 // for block or function pointer declaration. Name is aleady
4829 // part of the declaration.
4830 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4831 nameSize = 1;
4832 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4833 }
4834 else {
4835 SourceLocation startLoc;
4836 Expr *E = ND->getInit();
4837 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4838 startLoc = ECE->getLParenLoc();
4839 else
4840 startLoc = E->getLocStart();
4841 startLoc = SM->getExpansionLoc(startLoc);
4842 endBuf = SM->getCharacterData(startLoc);
4843 ByrefType += " " + Name;
4844 ByrefType += " = {(void*)";
4845 ByrefType += utostr(isa);
4846 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4847 ByrefType += utostr(flags);
4848 ByrefType += ", ";
4849 ByrefType += "sizeof(";
4850 RewriteByRefString(ByrefType, Name, ND);
4851 ByrefType += "), ";
4852 if (HasCopyAndDispose) {
4853 ByrefType += "__Block_byref_id_object_copy_";
4854 ByrefType += utostr(flag);
4855 ByrefType += ", __Block_byref_id_object_dispose_";
4856 ByrefType += utostr(flag);
4857 ByrefType += ", ";
4858 }
4859 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4860
4861 // Complete the newly synthesized compound expression by inserting a right
4862 // curly brace before the end of the declaration.
4863 // FIXME: This approach avoids rewriting the initializer expression. It
4864 // also assumes there is only one declarator. For example, the following
4865 // isn't currently supported by this routine (in general):
4866 //
4867 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4868 //
4869 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4870 const char *semiBuf = strchr(startInitializerBuf, ';');
4871 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4872 SourceLocation semiLoc =
4873 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4874
4875 InsertText(semiLoc, "}");
4876 }
4877 return;
4878}
4879
4880void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4881 // Add initializers for any closure decl refs.
4882 GetBlockDeclRefExprs(Exp->getBody());
4883 if (BlockDeclRefs.size()) {
4884 // Unique all "by copy" declarations.
4885 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004886 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004887 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4888 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4889 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4890 }
4891 }
4892 // Unique all "by ref" declarations.
4893 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004894 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004895 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4896 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4897 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4898 }
4899 }
4900 // Find any imported blocks...they will need special attention.
4901 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004902 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004903 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4904 BlockDeclRefs[i]->getType()->isBlockPointerType())
4905 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4906 }
4907}
4908
4909FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4910 IdentifierInfo *ID = &Context->Idents.get(name);
4911 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4912 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4913 SourceLocation(), ID, FType, 0, SC_Extern,
4914 SC_None, false, false);
4915}
4916
4917Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004918 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004919
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004920 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004921
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004922 Blocks.push_back(Exp);
4923
4924 CollectBlockDeclRefInfo(Exp);
4925
4926 // Add inner imported variables now used in current block.
4927 int countOfInnerDecls = 0;
4928 if (!InnerBlockDeclRefs.empty()) {
4929 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004930 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004931 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004932 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004933 // We need to save the copied-in variables in nested
4934 // blocks because it is needed at the end for some of the API generations.
4935 // See SynthesizeBlockLiterals routine.
4936 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4937 BlockDeclRefs.push_back(Exp);
4938 BlockByCopyDeclsPtrSet.insert(VD);
4939 BlockByCopyDecls.push_back(VD);
4940 }
John McCallf4b88a42012-03-10 09:33:50 +00004941 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004942 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4943 BlockDeclRefs.push_back(Exp);
4944 BlockByRefDeclsPtrSet.insert(VD);
4945 BlockByRefDecls.push_back(VD);
4946 }
4947 }
4948 // Find any imported blocks...they will need special attention.
4949 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004950 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004951 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4952 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4953 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4954 }
4955 InnerDeclRefsCount.push_back(countOfInnerDecls);
4956
4957 std::string FuncName;
4958
4959 if (CurFunctionDef)
4960 FuncName = CurFunctionDef->getNameAsString();
4961 else if (CurMethodDef)
4962 BuildUniqueMethodName(FuncName, CurMethodDef);
4963 else if (GlobalVarDecl)
4964 FuncName = std::string(GlobalVarDecl->getNameAsString());
4965
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004966 bool GlobalBlockExpr =
4967 block->getDeclContext()->getRedeclContext()->isFileContext();
4968
4969 if (GlobalBlockExpr && !GlobalVarDecl) {
4970 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4971 GlobalBlockExpr = false;
4972 }
4973
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004974 std::string BlockNumber = utostr(Blocks.size()-1);
4975
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004976 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4977
4978 // Get a pointer to the function type so we can cast appropriately.
4979 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4980 QualType FType = Context->getPointerType(BFT);
4981
4982 FunctionDecl *FD;
4983 Expr *NewRep;
4984
4985 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004986 std::string Tag;
4987
4988 if (GlobalBlockExpr)
4989 Tag = "__global_";
4990 else
4991 Tag = "__";
4992 Tag += FuncName + "_block_impl_" + BlockNumber;
4993
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004994 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004995 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004996 SourceLocation());
4997
4998 SmallVector<Expr*, 4> InitExprs;
4999
5000 // Initialize the block function.
5001 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005002 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5003 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005004 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5005 CK_BitCast, Arg);
5006 InitExprs.push_back(castExpr);
5007
5008 // Initialize the block descriptor.
5009 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5010
5011 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5012 SourceLocation(), SourceLocation(),
5013 &Context->Idents.get(DescData.c_str()),
5014 Context->VoidPtrTy, 0,
5015 SC_Static, SC_None);
5016 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005017 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005018 Context->VoidPtrTy,
5019 VK_LValue,
5020 SourceLocation()),
5021 UO_AddrOf,
5022 Context->getPointerType(Context->VoidPtrTy),
5023 VK_RValue, OK_Ordinary,
5024 SourceLocation());
5025 InitExprs.push_back(DescRefExpr);
5026
5027 // Add initializers for any closure decl refs.
5028 if (BlockDeclRefs.size()) {
5029 Expr *Exp;
5030 // Output all "by copy" declarations.
5031 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5032 E = BlockByCopyDecls.end(); I != E; ++I) {
5033 if (isObjCType((*I)->getType())) {
5034 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5035 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005036 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5037 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005038 if (HasLocalVariableExternalStorage(*I)) {
5039 QualType QT = (*I)->getType();
5040 QT = Context->getPointerType(QT);
5041 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5042 OK_Ordinary, SourceLocation());
5043 }
5044 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5045 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005046 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5047 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005048 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5049 CK_BitCast, Arg);
5050 } else {
5051 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005052 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5053 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005054 if (HasLocalVariableExternalStorage(*I)) {
5055 QualType QT = (*I)->getType();
5056 QT = Context->getPointerType(QT);
5057 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5058 OK_Ordinary, SourceLocation());
5059 }
5060
5061 }
5062 InitExprs.push_back(Exp);
5063 }
5064 // Output all "by ref" declarations.
5065 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5066 E = BlockByRefDecls.end(); I != E; ++I) {
5067 ValueDecl *ND = (*I);
5068 std::string Name(ND->getNameAsString());
5069 std::string RecName;
5070 RewriteByRefString(RecName, Name, ND, true);
5071 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5072 + sizeof("struct"));
5073 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5074 SourceLocation(), SourceLocation(),
5075 II);
5076 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5077 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5078
5079 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005080 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005081 SourceLocation());
5082 bool isNestedCapturedVar = false;
5083 if (block)
5084 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5085 ce = block->capture_end(); ci != ce; ++ci) {
5086 const VarDecl *variable = ci->getVariable();
5087 if (variable == ND && ci->isNested()) {
5088 assert (ci->isByRef() &&
5089 "SynthBlockInitExpr - captured block variable is not byref");
5090 isNestedCapturedVar = true;
5091 break;
5092 }
5093 }
5094 // captured nested byref variable has its address passed. Do not take
5095 // its address again.
5096 if (!isNestedCapturedVar)
5097 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5098 Context->getPointerType(Exp->getType()),
5099 VK_RValue, OK_Ordinary, SourceLocation());
5100 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5101 InitExprs.push_back(Exp);
5102 }
5103 }
5104 if (ImportedBlockDecls.size()) {
5105 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5106 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5107 unsigned IntSize =
5108 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5109 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5110 Context->IntTy, SourceLocation());
5111 InitExprs.push_back(FlagExp);
5112 }
5113 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5114 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005115
5116 if (GlobalBlockExpr) {
5117 assert (GlobalConstructionExp == 0 &&
5118 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5119 GlobalConstructionExp = NewRep;
5120 NewRep = DRE;
5121 }
5122
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005123 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5124 Context->getPointerType(NewRep->getType()),
5125 VK_RValue, OK_Ordinary, SourceLocation());
5126 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5127 NewRep);
5128 BlockDeclRefs.clear();
5129 BlockByRefDecls.clear();
5130 BlockByRefDeclsPtrSet.clear();
5131 BlockByCopyDecls.clear();
5132 BlockByCopyDeclsPtrSet.clear();
5133 ImportedBlockDecls.clear();
5134 return NewRep;
5135}
5136
5137bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5138 if (const ObjCForCollectionStmt * CS =
5139 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5140 return CS->getElement() == DS;
5141 return false;
5142}
5143
5144//===----------------------------------------------------------------------===//
5145// Function Body / Expression rewriting
5146//===----------------------------------------------------------------------===//
5147
5148Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5149 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5150 isa<DoStmt>(S) || isa<ForStmt>(S))
5151 Stmts.push_back(S);
5152 else if (isa<ObjCForCollectionStmt>(S)) {
5153 Stmts.push_back(S);
5154 ObjCBcLabelNo.push_back(++BcLabelCount);
5155 }
5156
5157 // Pseudo-object operations and ivar references need special
5158 // treatment because we're going to recursively rewrite them.
5159 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5160 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5161 return RewritePropertyOrImplicitSetter(PseudoOp);
5162 } else {
5163 return RewritePropertyOrImplicitGetter(PseudoOp);
5164 }
5165 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5166 return RewriteObjCIvarRefExpr(IvarRefExpr);
5167 }
5168
5169 SourceRange OrigStmtRange = S->getSourceRange();
5170
5171 // Perform a bottom up rewrite of all children.
5172 for (Stmt::child_range CI = S->children(); CI; ++CI)
5173 if (*CI) {
5174 Stmt *childStmt = (*CI);
5175 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5176 if (newStmt) {
5177 *CI = newStmt;
5178 }
5179 }
5180
5181 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005182 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005183 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5184 InnerContexts.insert(BE->getBlockDecl());
5185 ImportedLocalExternalDecls.clear();
5186 GetInnerBlockDeclRefExprs(BE->getBody(),
5187 InnerBlockDeclRefs, InnerContexts);
5188 // Rewrite the block body in place.
5189 Stmt *SaveCurrentBody = CurrentBody;
5190 CurrentBody = BE->getBody();
5191 PropParentMap = 0;
5192 // block literal on rhs of a property-dot-sytax assignment
5193 // must be replaced by its synthesize ast so getRewrittenText
5194 // works as expected. In this case, what actually ends up on RHS
5195 // is the blockTranscribed which is the helper function for the
5196 // block literal; as in: self.c = ^() {[ace ARR];};
5197 bool saveDisableReplaceStmt = DisableReplaceStmt;
5198 DisableReplaceStmt = false;
5199 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5200 DisableReplaceStmt = saveDisableReplaceStmt;
5201 CurrentBody = SaveCurrentBody;
5202 PropParentMap = 0;
5203 ImportedLocalExternalDecls.clear();
5204 // Now we snarf the rewritten text and stash it away for later use.
5205 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5206 RewrittenBlockExprs[BE] = Str;
5207
5208 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5209
5210 //blockTranscribed->dump();
5211 ReplaceStmt(S, blockTranscribed);
5212 return blockTranscribed;
5213 }
5214 // Handle specific things.
5215 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5216 return RewriteAtEncode(AtEncode);
5217
5218 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5219 return RewriteAtSelector(AtSelector);
5220
5221 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5222 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005223
5224 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5225 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005226
5227 if (ObjCNumericLiteral *NumericLitExpr = dyn_cast<ObjCNumericLiteral>(S))
5228 return RewriteObjCNumericLiteralExpr(NumericLitExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005229
5230 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5231 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005232
5233 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5234 dyn_cast<ObjCDictionaryLiteral>(S))
5235 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005236
5237 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5238#if 0
5239 // Before we rewrite it, put the original message expression in a comment.
5240 SourceLocation startLoc = MessExpr->getLocStart();
5241 SourceLocation endLoc = MessExpr->getLocEnd();
5242
5243 const char *startBuf = SM->getCharacterData(startLoc);
5244 const char *endBuf = SM->getCharacterData(endLoc);
5245
5246 std::string messString;
5247 messString += "// ";
5248 messString.append(startBuf, endBuf-startBuf+1);
5249 messString += "\n";
5250
5251 // FIXME: Missing definition of
5252 // InsertText(clang::SourceLocation, char const*, unsigned int).
5253 // InsertText(startLoc, messString.c_str(), messString.size());
5254 // Tried this, but it didn't work either...
5255 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5256#endif
5257 return RewriteMessageExpr(MessExpr);
5258 }
5259
5260 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5261 return RewriteObjCTryStmt(StmtTry);
5262
5263 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5264 return RewriteObjCSynchronizedStmt(StmtTry);
5265
5266 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5267 return RewriteObjCThrowStmt(StmtThrow);
5268
5269 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5270 return RewriteObjCProtocolExpr(ProtocolExp);
5271
5272 if (ObjCForCollectionStmt *StmtForCollection =
5273 dyn_cast<ObjCForCollectionStmt>(S))
5274 return RewriteObjCForCollectionStmt(StmtForCollection,
5275 OrigStmtRange.getEnd());
5276 if (BreakStmt *StmtBreakStmt =
5277 dyn_cast<BreakStmt>(S))
5278 return RewriteBreakStmt(StmtBreakStmt);
5279 if (ContinueStmt *StmtContinueStmt =
5280 dyn_cast<ContinueStmt>(S))
5281 return RewriteContinueStmt(StmtContinueStmt);
5282
5283 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5284 // and cast exprs.
5285 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5286 // FIXME: What we're doing here is modifying the type-specifier that
5287 // precedes the first Decl. In the future the DeclGroup should have
5288 // a separate type-specifier that we can rewrite.
5289 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5290 // the context of an ObjCForCollectionStmt. For example:
5291 // NSArray *someArray;
5292 // for (id <FooProtocol> index in someArray) ;
5293 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5294 // and it depends on the original text locations/positions.
5295 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5296 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5297
5298 // Blocks rewrite rules.
5299 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5300 DI != DE; ++DI) {
5301 Decl *SD = *DI;
5302 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5303 if (isTopLevelBlockPointerType(ND->getType()))
5304 RewriteBlockPointerDecl(ND);
5305 else if (ND->getType()->isFunctionPointerType())
5306 CheckFunctionPointerDecl(ND->getType(), ND);
5307 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5308 if (VD->hasAttr<BlocksAttr>()) {
5309 static unsigned uniqueByrefDeclCount = 0;
5310 assert(!BlockByRefDeclNo.count(ND) &&
5311 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5312 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5313 RewriteByRefVar(VD);
5314 }
5315 else
5316 RewriteTypeOfDecl(VD);
5317 }
5318 }
5319 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5320 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5321 RewriteBlockPointerDecl(TD);
5322 else if (TD->getUnderlyingType()->isFunctionPointerType())
5323 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5324 }
5325 }
5326 }
5327
5328 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5329 RewriteObjCQualifiedInterfaceTypes(CE);
5330
5331 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5332 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5333 assert(!Stmts.empty() && "Statement stack is empty");
5334 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5335 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5336 && "Statement stack mismatch");
5337 Stmts.pop_back();
5338 }
5339 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005340 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5341 ValueDecl *VD = DRE->getDecl();
5342 if (VD->hasAttr<BlocksAttr>())
5343 return RewriteBlockDeclRefExpr(DRE);
5344 if (HasLocalVariableExternalStorage(VD))
5345 return RewriteLocalVariableExternalStorage(DRE);
5346 }
5347
5348 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5349 if (CE->getCallee()->getType()->isBlockPointerType()) {
5350 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5351 ReplaceStmt(S, BlockCall);
5352 return BlockCall;
5353 }
5354 }
5355 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5356 RewriteCastExpr(CE);
5357 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005358 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5359 RewriteImplicitCastObjCExpr(ICE);
5360 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005361#if 0
5362 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5363 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5364 ICE->getSubExpr(),
5365 SourceLocation());
5366 // Get the new text.
5367 std::string SStr;
5368 llvm::raw_string_ostream Buf(SStr);
5369 Replacement->printPretty(Buf, *Context);
5370 const std::string &Str = Buf.str();
5371
5372 printf("CAST = %s\n", &Str[0]);
5373 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5374 delete S;
5375 return Replacement;
5376 }
5377#endif
5378 // Return this stmt unmodified.
5379 return S;
5380}
5381
5382void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5383 for (RecordDecl::field_iterator i = RD->field_begin(),
5384 e = RD->field_end(); i != e; ++i) {
5385 FieldDecl *FD = *i;
5386 if (isTopLevelBlockPointerType(FD->getType()))
5387 RewriteBlockPointerDecl(FD);
5388 if (FD->getType()->isObjCQualifiedIdType() ||
5389 FD->getType()->isObjCQualifiedInterfaceType())
5390 RewriteObjCQualifiedInterfaceTypes(FD);
5391 }
5392}
5393
5394/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5395/// main file of the input.
5396void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5397 switch (D->getKind()) {
5398 case Decl::Function: {
5399 FunctionDecl *FD = cast<FunctionDecl>(D);
5400 if (FD->isOverloadedOperator())
5401 return;
5402
5403 // Since function prototypes don't have ParmDecl's, we check the function
5404 // prototype. This enables us to rewrite function declarations and
5405 // definitions using the same code.
5406 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5407
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005408 if (!FD->isThisDeclarationADefinition())
5409 break;
5410
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005411 // FIXME: If this should support Obj-C++, support CXXTryStmt
5412 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5413 CurFunctionDef = FD;
5414 CurFunctionDeclToDeclareForBlock = FD;
5415 CurrentBody = Body;
5416 Body =
5417 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5418 FD->setBody(Body);
5419 CurrentBody = 0;
5420 if (PropParentMap) {
5421 delete PropParentMap;
5422 PropParentMap = 0;
5423 }
5424 // This synthesizes and inserts the block "impl" struct, invoke function,
5425 // and any copy/dispose helper functions.
5426 InsertBlockLiteralsWithinFunction(FD);
5427 CurFunctionDef = 0;
5428 CurFunctionDeclToDeclareForBlock = 0;
5429 }
5430 break;
5431 }
5432 case Decl::ObjCMethod: {
5433 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5434 if (CompoundStmt *Body = MD->getCompoundBody()) {
5435 CurMethodDef = MD;
5436 CurrentBody = Body;
5437 Body =
5438 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5439 MD->setBody(Body);
5440 CurrentBody = 0;
5441 if (PropParentMap) {
5442 delete PropParentMap;
5443 PropParentMap = 0;
5444 }
5445 InsertBlockLiteralsWithinMethod(MD);
5446 CurMethodDef = 0;
5447 }
5448 break;
5449 }
5450 case Decl::ObjCImplementation: {
5451 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5452 ClassImplementation.push_back(CI);
5453 break;
5454 }
5455 case Decl::ObjCCategoryImpl: {
5456 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5457 CategoryImplementation.push_back(CI);
5458 break;
5459 }
5460 case Decl::Var: {
5461 VarDecl *VD = cast<VarDecl>(D);
5462 RewriteObjCQualifiedInterfaceTypes(VD);
5463 if (isTopLevelBlockPointerType(VD->getType()))
5464 RewriteBlockPointerDecl(VD);
5465 else if (VD->getType()->isFunctionPointerType()) {
5466 CheckFunctionPointerDecl(VD->getType(), VD);
5467 if (VD->getInit()) {
5468 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5469 RewriteCastExpr(CE);
5470 }
5471 }
5472 } else if (VD->getType()->isRecordType()) {
5473 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5474 if (RD->isCompleteDefinition())
5475 RewriteRecordBody(RD);
5476 }
5477 if (VD->getInit()) {
5478 GlobalVarDecl = VD;
5479 CurrentBody = VD->getInit();
5480 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5481 CurrentBody = 0;
5482 if (PropParentMap) {
5483 delete PropParentMap;
5484 PropParentMap = 0;
5485 }
5486 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5487 GlobalVarDecl = 0;
5488
5489 // This is needed for blocks.
5490 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5491 RewriteCastExpr(CE);
5492 }
5493 }
5494 break;
5495 }
5496 case Decl::TypeAlias:
5497 case Decl::Typedef: {
5498 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5499 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5500 RewriteBlockPointerDecl(TD);
5501 else if (TD->getUnderlyingType()->isFunctionPointerType())
5502 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5503 }
5504 break;
5505 }
5506 case Decl::CXXRecord:
5507 case Decl::Record: {
5508 RecordDecl *RD = cast<RecordDecl>(D);
5509 if (RD->isCompleteDefinition())
5510 RewriteRecordBody(RD);
5511 break;
5512 }
5513 default:
5514 break;
5515 }
5516 // Nothing yet.
5517}
5518
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005519/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5520/// protocol reference symbols in the for of:
5521/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5522static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5523 ObjCProtocolDecl *PDecl,
5524 std::string &Result) {
5525 // Also output .objc_protorefs$B section and its meta-data.
5526 if (Context->getLangOpts().MicrosoftExt)
5527 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5528 Result += "struct _protocol_t *";
5529 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5530 Result += PDecl->getNameAsString();
5531 Result += " = &";
5532 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5533 Result += ";\n";
5534}
5535
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005536void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5537 if (Diags.hasErrorOccurred())
5538 return;
5539
5540 RewriteInclude();
5541
5542 // Here's a great place to add any extra declarations that may be needed.
5543 // Write out meta data for each @protocol(<expr>).
5544 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005545 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005546 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005547 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5548 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005549
5550 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005551 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5552 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5553 // Write struct declaration for the class matching its ivar declarations.
5554 // Note that for modern abi, this is postponed until the end of TU
5555 // because class extensions and the implementation might declare their own
5556 // private ivars.
5557 RewriteInterfaceDecl(CDecl);
5558 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005559
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005560 if (ClassImplementation.size() || CategoryImplementation.size())
5561 RewriteImplementations();
5562
5563 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5564 // we are done.
5565 if (const RewriteBuffer *RewriteBuf =
5566 Rewrite.getRewriteBufferFor(MainFileID)) {
5567 //printf("Changed:\n");
5568 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5569 } else {
5570 llvm::errs() << "No changes\n";
5571 }
5572
5573 if (ClassImplementation.size() || CategoryImplementation.size() ||
5574 ProtocolExprDecls.size()) {
5575 // Rewrite Objective-c meta data*
5576 std::string ResultStr;
5577 RewriteMetaDataIntoBuffer(ResultStr);
5578 // Emit metadata.
5579 *OutFile << ResultStr;
5580 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005581 // Emit ImageInfo;
5582 {
5583 std::string ResultStr;
5584 WriteImageInfo(ResultStr);
5585 *OutFile << ResultStr;
5586 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005587 OutFile->flush();
5588}
5589
5590void RewriteModernObjC::Initialize(ASTContext &context) {
5591 InitializeCommon(context);
5592
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005593 Preamble += "#ifndef __OBJC2__\n";
5594 Preamble += "#define __OBJC2__\n";
5595 Preamble += "#endif\n";
5596
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005597 // declaring objc_selector outside the parameter list removes a silly
5598 // scope related warning...
5599 if (IsHeader)
5600 Preamble = "#pragma once\n";
5601 Preamble += "struct objc_selector; struct objc_class;\n";
5602 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5603 Preamble += "struct objc_object *superClass; ";
5604 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005605 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005606 // These are currently generated.
5607 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005608 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005609 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5610 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005611 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5612 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005613 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005614 // These are generated but not necessary for functionality.
5615 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5616 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005617 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5618 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005619 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005620
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005621 // These need be generated for performance. Currently they are not,
5622 // using API calls instead.
5623 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5624 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5625 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5626
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005627 // Add a constructor for creating temporary objects.
5628 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5629 ": ";
5630 Preamble += "object(o), superClass(s) {} ";
5631 }
5632 Preamble += "};\n";
5633 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5634 Preamble += "typedef struct objc_object Protocol;\n";
5635 Preamble += "#define _REWRITER_typedef_Protocol\n";
5636 Preamble += "#endif\n";
5637 if (LangOpts.MicrosoftExt) {
5638 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5639 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005640 }
5641 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005642 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005643
5644 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5645 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5646 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5647 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5648 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5649
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005650 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5651 Preamble += "(const char *);\n";
5652 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5653 Preamble += "(struct objc_class *);\n";
5654 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5655 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005656 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005657 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005658 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5659 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005660 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5661 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5662 Preamble += "struct __objcFastEnumerationState {\n\t";
5663 Preamble += "unsigned long state;\n\t";
5664 Preamble += "void **itemsPtr;\n\t";
5665 Preamble += "unsigned long *mutationsPtr;\n\t";
5666 Preamble += "unsigned long extra[5];\n};\n";
5667 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5668 Preamble += "#define __FASTENUMERATIONSTATE\n";
5669 Preamble += "#endif\n";
5670 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5671 Preamble += "struct __NSConstantStringImpl {\n";
5672 Preamble += " int *isa;\n";
5673 Preamble += " int flags;\n";
5674 Preamble += " char *str;\n";
5675 Preamble += " long length;\n";
5676 Preamble += "};\n";
5677 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5678 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5679 Preamble += "#else\n";
5680 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5681 Preamble += "#endif\n";
5682 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5683 Preamble += "#endif\n";
5684 // Blocks preamble.
5685 Preamble += "#ifndef BLOCK_IMPL\n";
5686 Preamble += "#define BLOCK_IMPL\n";
5687 Preamble += "struct __block_impl {\n";
5688 Preamble += " void *isa;\n";
5689 Preamble += " int Flags;\n";
5690 Preamble += " int Reserved;\n";
5691 Preamble += " void *FuncPtr;\n";
5692 Preamble += "};\n";
5693 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5694 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5695 Preamble += "extern \"C\" __declspec(dllexport) "
5696 "void _Block_object_assign(void *, const void *, const int);\n";
5697 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5698 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5699 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5700 Preamble += "#else\n";
5701 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5702 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5703 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5704 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5705 Preamble += "#endif\n";
5706 Preamble += "#endif\n";
5707 if (LangOpts.MicrosoftExt) {
5708 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5709 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5710 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5711 Preamble += "#define __attribute__(X)\n";
5712 Preamble += "#endif\n";
5713 Preamble += "#define __weak\n";
5714 }
5715 else {
5716 Preamble += "#define __block\n";
5717 Preamble += "#define __weak\n";
5718 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005719
5720 // Declarations required for modern objective-c array and dictionary literals.
5721 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005722 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005723 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005724 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005725 Preamble += "\tva_list marker;\n";
5726 Preamble += "\tva_start(marker, count);\n";
5727 Preamble += "\tarr = new void *[count];\n";
5728 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5729 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5730 Preamble += "\tva_end( marker );\n";
5731 Preamble += " };\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005732 Preamble += " __NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005733 Preamble += "\tdelete[] arr;\n";
5734 Preamble += " }\n";
5735 Preamble += "};\n";
5736
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005737 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5738 // as this avoids warning in any 64bit/32bit compilation model.
5739 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5740}
5741
5742/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5743/// ivar offset.
5744void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5745 std::string &Result) {
5746 if (ivar->isBitField()) {
5747 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5748 // place all bitfields at offset 0.
5749 Result += "0";
5750 } else {
5751 Result += "__OFFSETOFIVAR__(struct ";
5752 Result += ivar->getContainingInterface()->getNameAsString();
5753 if (LangOpts.MicrosoftExt)
5754 Result += "_IMPL";
5755 Result += ", ";
5756 Result += ivar->getNameAsString();
5757 Result += ")";
5758 }
5759}
5760
5761/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5762/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005763/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005764/// char *attributes;
5765/// }
5766
5767/// struct _prop_list_t {
5768/// uint32_t entsize; // sizeof(struct _prop_t)
5769/// uint32_t count_of_properties;
5770/// struct _prop_t prop_list[count_of_properties];
5771/// }
5772
5773/// struct _protocol_t;
5774
5775/// struct _protocol_list_t {
5776/// long protocol_count; // Note, this is 32/64 bit
5777/// struct _protocol_t * protocol_list[protocol_count];
5778/// }
5779
5780/// struct _objc_method {
5781/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005782/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005783/// char *_imp;
5784/// }
5785
5786/// struct _method_list_t {
5787/// uint32_t entsize; // sizeof(struct _objc_method)
5788/// uint32_t method_count;
5789/// struct _objc_method method_list[method_count];
5790/// }
5791
5792/// struct _protocol_t {
5793/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005794/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005795/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005796/// const struct method_list_t *instance_methods;
5797/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005798/// const struct method_list_t *optionalInstanceMethods;
5799/// const struct method_list_t *optionalClassMethods;
5800/// const struct _prop_list_t * properties;
5801/// const uint32_t size; // sizeof(struct _protocol_t)
5802/// const uint32_t flags; // = 0
5803/// const char ** extendedMethodTypes;
5804/// }
5805
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005806/// struct _ivar_t {
5807/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005808/// const char *name;
5809/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005810/// uint32_t alignment;
5811/// uint32_t size;
5812/// }
5813
5814/// struct _ivar_list_t {
5815/// uint32 entsize; // sizeof(struct _ivar_t)
5816/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005817/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005818/// }
5819
5820/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005821/// uint32_t flags;
5822/// uint32_t instanceStart;
5823/// uint32_t instanceSize;
5824/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005825/// const uint8_t *ivarLayout;
5826/// const char *name;
5827/// const struct _method_list_t *baseMethods;
5828/// const struct _protocol_list_t *baseProtocols;
5829/// const struct _ivar_list_t *ivars;
5830/// const uint8_t *weakIvarLayout;
5831/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005832/// }
5833
5834/// struct _class_t {
5835/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005836/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005837/// void *cache;
5838/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005839/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005840/// }
5841
5842/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005843/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005844/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005845/// const struct _method_list_t *instance_methods;
5846/// const struct _method_list_t *class_methods;
5847/// const struct _protocol_list_t *protocols;
5848/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005849/// }
5850
5851/// MessageRefTy - LLVM for:
5852/// struct _message_ref_t {
5853/// IMP messenger;
5854/// SEL name;
5855/// };
5856
5857/// SuperMessageRefTy - LLVM for:
5858/// struct _super_message_ref_t {
5859/// SUPER_IMP messenger;
5860/// SEL name;
5861/// };
5862
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005863static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005864 static bool meta_data_declared = false;
5865 if (meta_data_declared)
5866 return;
5867
5868 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005869 Result += "\tconst char *name;\n";
5870 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005871 Result += "};\n";
5872
5873 Result += "\nstruct _protocol_t;\n";
5874
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005875 Result += "\nstruct _objc_method {\n";
5876 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005877 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005878 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005879 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005880
5881 Result += "\nstruct _protocol_t {\n";
5882 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005883 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005884 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005885 Result += "\tconst struct method_list_t *instance_methods;\n";
5886 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005887 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5888 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5889 Result += "\tconst struct _prop_list_t * properties;\n";
5890 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5891 Result += "\tconst unsigned int flags; // = 0\n";
5892 Result += "\tconst char ** extendedMethodTypes;\n";
5893 Result += "};\n";
5894
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005895 Result += "\nstruct _ivar_t {\n";
5896 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005897 Result += "\tconst char *name;\n";
5898 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005899 Result += "\tunsigned int alignment;\n";
5900 Result += "\tunsigned int size;\n";
5901 Result += "};\n";
5902
5903 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005904 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005905 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005906 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005907 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5908 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005909 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005910 Result += "\tconst unsigned char *ivarLayout;\n";
5911 Result += "\tconst char *name;\n";
5912 Result += "\tconst struct _method_list_t *baseMethods;\n";
5913 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5914 Result += "\tconst struct _ivar_list_t *ivars;\n";
5915 Result += "\tconst unsigned char *weakIvarLayout;\n";
5916 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005917 Result += "};\n";
5918
5919 Result += "\nstruct _class_t {\n";
5920 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005921 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005922 Result += "\tvoid *cache;\n";
5923 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005924 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005925 Result += "};\n";
5926
5927 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005928 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005929 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005930 Result += "\tconst struct _method_list_t *instance_methods;\n";
5931 Result += "\tconst struct _method_list_t *class_methods;\n";
5932 Result += "\tconst struct _protocol_list_t *protocols;\n";
5933 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005934 Result += "};\n";
5935
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005936 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005937 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005938 meta_data_declared = true;
5939}
5940
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005941static void Write_protocol_list_t_TypeDecl(std::string &Result,
5942 long super_protocol_count) {
5943 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5944 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5945 Result += "\tstruct _protocol_t *super_protocols[";
5946 Result += utostr(super_protocol_count); Result += "];\n";
5947 Result += "}";
5948}
5949
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005950static void Write_method_list_t_TypeDecl(std::string &Result,
5951 unsigned int method_count) {
5952 Result += "struct /*_method_list_t*/"; Result += " {\n";
5953 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5954 Result += "\tunsigned int method_count;\n";
5955 Result += "\tstruct _objc_method method_list[";
5956 Result += utostr(method_count); Result += "];\n";
5957 Result += "}";
5958}
5959
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005960static void Write__prop_list_t_TypeDecl(std::string &Result,
5961 unsigned int property_count) {
5962 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5963 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5964 Result += "\tunsigned int count_of_properties;\n";
5965 Result += "\tstruct _prop_t prop_list[";
5966 Result += utostr(property_count); Result += "];\n";
5967 Result += "}";
5968}
5969
Fariborz Jahanianae932952012-02-10 20:47:10 +00005970static void Write__ivar_list_t_TypeDecl(std::string &Result,
5971 unsigned int ivar_count) {
5972 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5973 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5974 Result += "\tunsigned int count;\n";
5975 Result += "\tstruct _ivar_t ivar_list[";
5976 Result += utostr(ivar_count); Result += "];\n";
5977 Result += "}";
5978}
5979
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005980static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5981 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5982 StringRef VarName,
5983 StringRef ProtocolName) {
5984 if (SuperProtocols.size() > 0) {
5985 Result += "\nstatic ";
5986 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5987 Result += " "; Result += VarName;
5988 Result += ProtocolName;
5989 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5990 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5991 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5992 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5993 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5994 Result += SuperPD->getNameAsString();
5995 if (i == e-1)
5996 Result += "\n};\n";
5997 else
5998 Result += ",\n";
5999 }
6000 }
6001}
6002
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006003static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6004 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006005 ArrayRef<ObjCMethodDecl *> Methods,
6006 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006007 StringRef TopLevelDeclName,
6008 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006009 if (Methods.size() > 0) {
6010 Result += "\nstatic ";
6011 Write_method_list_t_TypeDecl(Result, Methods.size());
6012 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006013 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006014 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6015 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6016 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6017 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6018 ObjCMethodDecl *MD = Methods[i];
6019 if (i == 0)
6020 Result += "\t{{(struct objc_selector *)\"";
6021 else
6022 Result += "\t{(struct objc_selector *)\"";
6023 Result += (MD)->getSelector().getAsString(); Result += "\"";
6024 Result += ", ";
6025 std::string MethodTypeString;
6026 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6027 Result += "\""; Result += MethodTypeString; Result += "\"";
6028 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006029 if (!MethodImpl)
6030 Result += "0";
6031 else {
6032 Result += "(void *)";
6033 Result += RewriteObj.MethodInternalNames[MD];
6034 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006035 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006036 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006037 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006038 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006039 }
6040 Result += "};\n";
6041 }
6042}
6043
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006044static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006045 ASTContext *Context, std::string &Result,
6046 ArrayRef<ObjCPropertyDecl *> Properties,
6047 const Decl *Container,
6048 StringRef VarName,
6049 StringRef ProtocolName) {
6050 if (Properties.size() > 0) {
6051 Result += "\nstatic ";
6052 Write__prop_list_t_TypeDecl(Result, Properties.size());
6053 Result += " "; Result += VarName;
6054 Result += ProtocolName;
6055 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6056 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6057 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6058 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6059 ObjCPropertyDecl *PropDecl = Properties[i];
6060 if (i == 0)
6061 Result += "\t{{\"";
6062 else
6063 Result += "\t{\"";
6064 Result += PropDecl->getName(); Result += "\",";
6065 std::string PropertyTypeString, QuotePropertyTypeString;
6066 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6067 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6068 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6069 if (i == e-1)
6070 Result += "}}\n";
6071 else
6072 Result += "},\n";
6073 }
6074 Result += "};\n";
6075 }
6076}
6077
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006078// Metadata flags
6079enum MetaDataDlags {
6080 CLS = 0x0,
6081 CLS_META = 0x1,
6082 CLS_ROOT = 0x2,
6083 OBJC2_CLS_HIDDEN = 0x10,
6084 CLS_EXCEPTION = 0x20,
6085
6086 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6087 CLS_HAS_IVAR_RELEASER = 0x40,
6088 /// class was compiled with -fobjc-arr
6089 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6090};
6091
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006092static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6093 unsigned int flags,
6094 const std::string &InstanceStart,
6095 const std::string &InstanceSize,
6096 ArrayRef<ObjCMethodDecl *>baseMethods,
6097 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6098 ArrayRef<ObjCIvarDecl *>ivars,
6099 ArrayRef<ObjCPropertyDecl *>Properties,
6100 StringRef VarName,
6101 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006102 Result += "\nstatic struct _class_ro_t ";
6103 Result += VarName; Result += ClassName;
6104 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6105 Result += "\t";
6106 Result += llvm::utostr(flags); Result += ", ";
6107 Result += InstanceStart; Result += ", ";
6108 Result += InstanceSize; Result += ", \n";
6109 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006110 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6111 if (Triple.getArch() == llvm::Triple::x86_64)
6112 // uint32_t const reserved; // only when building for 64bit targets
6113 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006114 // const uint8_t * const ivarLayout;
6115 Result += "0, \n\t";
6116 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006117 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006118 if (baseMethods.size() > 0) {
6119 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006120 if (metaclass)
6121 Result += "_OBJC_$_CLASS_METHODS_";
6122 else
6123 Result += "_OBJC_$_INSTANCE_METHODS_";
6124 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006125 Result += ",\n\t";
6126 }
6127 else
6128 Result += "0, \n\t";
6129
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006130 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006131 Result += "(const struct _objc_protocol_list *)&";
6132 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6133 Result += ",\n\t";
6134 }
6135 else
6136 Result += "0, \n\t";
6137
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006138 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006139 Result += "(const struct _ivar_list_t *)&";
6140 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6141 Result += ",\n\t";
6142 }
6143 else
6144 Result += "0, \n\t";
6145
6146 // weakIvarLayout
6147 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006148 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006149 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006150 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006151 Result += ",\n";
6152 }
6153 else
6154 Result += "0, \n";
6155
6156 Result += "};\n";
6157}
6158
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006159static void Write_class_t(ASTContext *Context, std::string &Result,
6160 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006161 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6162 bool rootClass = (!CDecl->getSuperClass());
6163 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006164
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006165 if (!rootClass) {
6166 // Find the Root class
6167 RootClass = CDecl->getSuperClass();
6168 while (RootClass->getSuperClass()) {
6169 RootClass = RootClass->getSuperClass();
6170 }
6171 }
6172
6173 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006174 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006175 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006176 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006177 if (CDecl->getImplementation())
6178 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006179 else
6180 Result += "__declspec(dllimport) ";
6181
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006182 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006183 Result += CDecl->getNameAsString();
6184 Result += ";\n";
6185 }
6186 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006187 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006188 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006189 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006190 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006191 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006192 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006193 else
6194 Result += "__declspec(dllimport) ";
6195
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006196 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006197 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006198 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006199 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006200
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006201 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006202 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006203 if (RootClass->getImplementation())
6204 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006205 else
6206 Result += "__declspec(dllimport) ";
6207
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006208 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006209 Result += VarName;
6210 Result += RootClass->getNameAsString();
6211 Result += ";\n";
6212 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006213 }
6214
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006215 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6216 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006217 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6218 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006219 if (metaclass) {
6220 if (!rootClass) {
6221 Result += "0, // &"; Result += VarName;
6222 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006223 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006224 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006225 Result += CDecl->getSuperClass()->getNameAsString();
6226 Result += ",\n\t";
6227 }
6228 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006229 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006230 Result += CDecl->getNameAsString();
6231 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006232 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006233 Result += ",\n\t";
6234 }
6235 }
6236 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006237 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006238 Result += CDecl->getNameAsString();
6239 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006240 if (!rootClass) {
6241 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006242 Result += CDecl->getSuperClass()->getNameAsString();
6243 Result += ",\n\t";
6244 }
6245 else
6246 Result += "0,\n\t";
6247 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006248 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6249 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6250 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006251 Result += "&_OBJC_METACLASS_RO_$_";
6252 else
6253 Result += "&_OBJC_CLASS_RO_$_";
6254 Result += CDecl->getNameAsString();
6255 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006256
6257 // Add static function to initialize some of the meta-data fields.
6258 // avoid doing it twice.
6259 if (metaclass)
6260 return;
6261
6262 const ObjCInterfaceDecl *SuperClass =
6263 rootClass ? CDecl : CDecl->getSuperClass();
6264
6265 Result += "static void OBJC_CLASS_SETUP_$_";
6266 Result += CDecl->getNameAsString();
6267 Result += "(void ) {\n";
6268 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6269 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006270 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006271
6272 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006273 Result += ".superclass = ";
6274 if (rootClass)
6275 Result += "&OBJC_CLASS_$_";
6276 else
6277 Result += "&OBJC_METACLASS_$_";
6278
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006279 Result += SuperClass->getNameAsString(); Result += ";\n";
6280
6281 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6282 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6283
6284 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6285 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6286 Result += CDecl->getNameAsString(); Result += ";\n";
6287
6288 if (!rootClass) {
6289 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6290 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6291 Result += SuperClass->getNameAsString(); Result += ";\n";
6292 }
6293
6294 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6295 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6296 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006297}
6298
Fariborz Jahanian61186122012-02-17 18:40:41 +00006299static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6300 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006301 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006302 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006303 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6304 ArrayRef<ObjCMethodDecl *> ClassMethods,
6305 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6306 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006307 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006308 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006309 // must declare an extern class object in case this class is not implemented
6310 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006311 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006312 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006313 if (ClassDecl->getImplementation())
6314 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006315 else
6316 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006317
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006318 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006319 Result += "OBJC_CLASS_$_"; Result += ClassName;
6320 Result += ";\n";
6321
Fariborz Jahanian61186122012-02-17 18:40:41 +00006322 Result += "\nstatic struct _category_t ";
6323 Result += "_OBJC_$_CATEGORY_";
6324 Result += ClassName; Result += "_$_"; Result += CatName;
6325 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6326 Result += "{\n";
6327 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006328 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006329 Result += ",\n";
6330 if (InstanceMethods.size() > 0) {
6331 Result += "\t(const struct _method_list_t *)&";
6332 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6333 Result += ClassName; Result += "_$_"; Result += CatName;
6334 Result += ",\n";
6335 }
6336 else
6337 Result += "\t0,\n";
6338
6339 if (ClassMethods.size() > 0) {
6340 Result += "\t(const struct _method_list_t *)&";
6341 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6342 Result += ClassName; Result += "_$_"; Result += CatName;
6343 Result += ",\n";
6344 }
6345 else
6346 Result += "\t0,\n";
6347
6348 if (RefedProtocols.size() > 0) {
6349 Result += "\t(const struct _protocol_list_t *)&";
6350 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6351 Result += ClassName; Result += "_$_"; Result += CatName;
6352 Result += ",\n";
6353 }
6354 else
6355 Result += "\t0,\n";
6356
6357 if (ClassProperties.size() > 0) {
6358 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6359 Result += ClassName; Result += "_$_"; Result += CatName;
6360 Result += ",\n";
6361 }
6362 else
6363 Result += "\t0,\n";
6364
6365 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006366
6367 // Add static function to initialize the class pointer in the category structure.
6368 Result += "static void OBJC_CATEGORY_SETUP_$_";
6369 Result += ClassDecl->getNameAsString();
6370 Result += "_$_";
6371 Result += CatName;
6372 Result += "(void ) {\n";
6373 Result += "\t_OBJC_$_CATEGORY_";
6374 Result += ClassDecl->getNameAsString();
6375 Result += "_$_";
6376 Result += CatName;
6377 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6378 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006379}
6380
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006381static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6382 ASTContext *Context, std::string &Result,
6383 ArrayRef<ObjCMethodDecl *> Methods,
6384 StringRef VarName,
6385 StringRef ProtocolName) {
6386 if (Methods.size() == 0)
6387 return;
6388
6389 Result += "\nstatic const char *";
6390 Result += VarName; Result += ProtocolName;
6391 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6392 Result += "{\n";
6393 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6394 ObjCMethodDecl *MD = Methods[i];
6395 std::string MethodTypeString, QuoteMethodTypeString;
6396 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6397 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6398 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6399 if (i == e-1)
6400 Result += "\n};\n";
6401 else {
6402 Result += ",\n";
6403 }
6404 }
6405}
6406
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006407static void Write_IvarOffsetVar(ASTContext *Context,
6408 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006409 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006410 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006411 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6412 // this is what happens:
6413 /**
6414 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6415 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6416 Class->getVisibility() == HiddenVisibility)
6417 Visibility shoud be: HiddenVisibility;
6418 else
6419 Visibility shoud be: DefaultVisibility;
6420 */
6421
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006422 Result += "\n";
6423 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6424 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006425 if (Context->getLangOpts().MicrosoftExt)
6426 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6427
6428 if (!Context->getLangOpts().MicrosoftExt ||
6429 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006430 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006431 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006432 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006433 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006434 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006435 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6436 Result += " = ";
6437 if (IvarDecl->isBitField()) {
6438 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6439 // place all bitfields at offset 0.
6440 Result += "0;\n";
6441 }
6442 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006443 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006444 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006445 Result += "_IMPL, ";
6446 Result += IvarDecl->getName(); Result += ");\n";
6447 }
6448 }
6449}
6450
Fariborz Jahanianae932952012-02-10 20:47:10 +00006451static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6452 ASTContext *Context, std::string &Result,
6453 ArrayRef<ObjCIvarDecl *> Ivars,
6454 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006455 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006456 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006457 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006458
Fariborz Jahanianae932952012-02-10 20:47:10 +00006459 Result += "\nstatic ";
6460 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6461 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006462 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006463 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6464 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6465 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6466 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6467 ObjCIvarDecl *IvarDecl = Ivars[i];
6468 if (i == 0)
6469 Result += "\t{{";
6470 else
6471 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006472 Result += "(unsigned long int *)&";
6473 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006474 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006475
6476 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6477 std::string IvarTypeString, QuoteIvarTypeString;
6478 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6479 IvarDecl);
6480 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6481 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6482
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006483 // FIXME. this alignment represents the host alignment and need be changed to
6484 // represent the target alignment.
6485 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6486 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006487 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006488 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6489 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006490 if (i == e-1)
6491 Result += "}}\n";
6492 else
6493 Result += "},\n";
6494 }
6495 Result += "};\n";
6496 }
6497}
6498
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006499/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006500void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6501 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006502
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006503 // Do not synthesize the protocol more than once.
6504 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6505 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006506 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006507
6508 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6509 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006510 // Must write out all protocol definitions in current qualifier list,
6511 // and in their nested qualifiers before writing out current definition.
6512 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6513 E = PDecl->protocol_end(); I != E; ++I)
6514 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006515
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006516 // Construct method lists.
6517 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6518 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6519 for (ObjCProtocolDecl::instmeth_iterator
6520 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6521 I != E; ++I) {
6522 ObjCMethodDecl *MD = *I;
6523 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6524 OptInstanceMethods.push_back(MD);
6525 } else {
6526 InstanceMethods.push_back(MD);
6527 }
6528 }
6529
6530 for (ObjCProtocolDecl::classmeth_iterator
6531 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6532 I != E; ++I) {
6533 ObjCMethodDecl *MD = *I;
6534 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6535 OptClassMethods.push_back(MD);
6536 } else {
6537 ClassMethods.push_back(MD);
6538 }
6539 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006540 std::vector<ObjCMethodDecl *> AllMethods;
6541 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6542 AllMethods.push_back(InstanceMethods[i]);
6543 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6544 AllMethods.push_back(ClassMethods[i]);
6545 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6546 AllMethods.push_back(OptInstanceMethods[i]);
6547 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6548 AllMethods.push_back(OptClassMethods[i]);
6549
6550 Write__extendedMethodTypes_initializer(*this, Context, Result,
6551 AllMethods,
6552 "_OBJC_PROTOCOL_METHOD_TYPES_",
6553 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006554 // Protocol's super protocol list
6555 std::vector<ObjCProtocolDecl *> SuperProtocols;
6556 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6557 E = PDecl->protocol_end(); I != E; ++I)
6558 SuperProtocols.push_back(*I);
6559
6560 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6561 "_OBJC_PROTOCOL_REFS_",
6562 PDecl->getNameAsString());
6563
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006564 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006565 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006566 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006567
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006568 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006569 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006570 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006571
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006572 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006573 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006574 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006575
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006576 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006577 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006578 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006579
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006580 // Protocol's property metadata.
6581 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6582 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6583 E = PDecl->prop_end(); I != E; ++I)
6584 ProtocolProperties.push_back(*I);
6585
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006586 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006587 /* Container */0,
6588 "_OBJC_PROTOCOL_PROPERTIES_",
6589 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006590
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006591 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006592 Result += "\n";
6593 if (LangOpts.MicrosoftExt)
6594 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006595 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006596 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006597 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6598 Result += "\t0,\n"; // id is; is null
6599 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006600 if (SuperProtocols.size() > 0) {
6601 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6602 Result += PDecl->getNameAsString(); Result += ",\n";
6603 }
6604 else
6605 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006606 if (InstanceMethods.size() > 0) {
6607 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6608 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006609 }
6610 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006611 Result += "\t0,\n";
6612
6613 if (ClassMethods.size() > 0) {
6614 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6615 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006616 }
6617 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006618 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006619
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006620 if (OptInstanceMethods.size() > 0) {
6621 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6622 Result += PDecl->getNameAsString(); Result += ",\n";
6623 }
6624 else
6625 Result += "\t0,\n";
6626
6627 if (OptClassMethods.size() > 0) {
6628 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6629 Result += PDecl->getNameAsString(); Result += ",\n";
6630 }
6631 else
6632 Result += "\t0,\n";
6633
6634 if (ProtocolProperties.size() > 0) {
6635 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6636 Result += PDecl->getNameAsString(); Result += ",\n";
6637 }
6638 else
6639 Result += "\t0,\n";
6640
6641 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6642 Result += "\t0,\n";
6643
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006644 if (AllMethods.size() > 0) {
6645 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6646 Result += PDecl->getNameAsString();
6647 Result += "\n};\n";
6648 }
6649 else
6650 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006651
6652 // Use this protocol meta-data to build protocol list table in section
6653 // .objc_protolist$B
6654 // Unspecified visibility means 'private extern'.
6655 if (LangOpts.MicrosoftExt)
6656 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6657 Result += "struct _protocol_t *";
6658 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6659 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6660 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006661
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006662 // Mark this protocol as having been generated.
6663 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6664 llvm_unreachable("protocol already synthesized");
6665
6666}
6667
6668void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6669 const ObjCList<ObjCProtocolDecl> &Protocols,
6670 StringRef prefix, StringRef ClassName,
6671 std::string &Result) {
6672 if (Protocols.empty()) return;
6673
6674 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006675 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006676
6677 // Output the top lovel protocol meta-data for the class.
6678 /* struct _objc_protocol_list {
6679 struct _objc_protocol_list *next;
6680 int protocol_count;
6681 struct _objc_protocol *class_protocols[];
6682 }
6683 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006684 Result += "\n";
6685 if (LangOpts.MicrosoftExt)
6686 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6687 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006688 Result += "\tstruct _objc_protocol_list *next;\n";
6689 Result += "\tint protocol_count;\n";
6690 Result += "\tstruct _objc_protocol *class_protocols[";
6691 Result += utostr(Protocols.size());
6692 Result += "];\n} _OBJC_";
6693 Result += prefix;
6694 Result += "_PROTOCOLS_";
6695 Result += ClassName;
6696 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6697 "{\n\t0, ";
6698 Result += utostr(Protocols.size());
6699 Result += "\n";
6700
6701 Result += "\t,{&_OBJC_PROTOCOL_";
6702 Result += Protocols[0]->getNameAsString();
6703 Result += " \n";
6704
6705 for (unsigned i = 1; i != Protocols.size(); i++) {
6706 Result += "\t ,&_OBJC_PROTOCOL_";
6707 Result += Protocols[i]->getNameAsString();
6708 Result += "\n";
6709 }
6710 Result += "\t }\n};\n";
6711}
6712
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006713/// hasObjCExceptionAttribute - Return true if this class or any super
6714/// class has the __objc_exception__ attribute.
6715/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6716static bool hasObjCExceptionAttribute(ASTContext &Context,
6717 const ObjCInterfaceDecl *OID) {
6718 if (OID->hasAttr<ObjCExceptionAttr>())
6719 return true;
6720 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6721 return hasObjCExceptionAttribute(Context, Super);
6722 return false;
6723}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006724
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006725void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6726 std::string &Result) {
6727 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6728
6729 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006730 if (CDecl->isImplicitInterfaceDecl())
6731 assert(false &&
6732 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006733
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006734 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006735 SmallVector<ObjCIvarDecl *, 8> IVars;
6736
6737 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6738 IVD; IVD = IVD->getNextIvar()) {
6739 // Ignore unnamed bit-fields.
6740 if (!IVD->getDeclName())
6741 continue;
6742 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006743 }
6744
Fariborz Jahanianae932952012-02-10 20:47:10 +00006745 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006746 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006747 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006748
6749 // Build _objc_method_list for class's instance methods if needed
6750 SmallVector<ObjCMethodDecl *, 32>
6751 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6752
6753 // If any of our property implementations have associated getters or
6754 // setters, produce metadata for them as well.
6755 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6756 PropEnd = IDecl->propimpl_end();
6757 Prop != PropEnd; ++Prop) {
6758 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6759 continue;
6760 if (!(*Prop)->getPropertyIvarDecl())
6761 continue;
6762 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6763 if (!PD)
6764 continue;
6765 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6766 if (!Getter->isDefined())
6767 InstanceMethods.push_back(Getter);
6768 if (PD->isReadOnly())
6769 continue;
6770 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6771 if (!Setter->isDefined())
6772 InstanceMethods.push_back(Setter);
6773 }
6774
6775 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6776 "_OBJC_$_INSTANCE_METHODS_",
6777 IDecl->getNameAsString(), true);
6778
6779 SmallVector<ObjCMethodDecl *, 32>
6780 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6781
6782 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6783 "_OBJC_$_CLASS_METHODS_",
6784 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006785
6786 // Protocols referenced in class declaration?
6787 // Protocol's super protocol list
6788 std::vector<ObjCProtocolDecl *> RefedProtocols;
6789 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6790 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6791 E = Protocols.end();
6792 I != E; ++I) {
6793 RefedProtocols.push_back(*I);
6794 // Must write out all protocol definitions in current qualifier list,
6795 // and in their nested qualifiers before writing out current definition.
6796 RewriteObjCProtocolMetaData(*I, Result);
6797 }
6798
6799 Write_protocol_list_initializer(Context, Result,
6800 RefedProtocols,
6801 "_OBJC_CLASS_PROTOCOLS_$_",
6802 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006803
6804 // Protocol's property metadata.
6805 std::vector<ObjCPropertyDecl *> ClassProperties;
6806 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6807 E = CDecl->prop_end(); I != E; ++I)
6808 ClassProperties.push_back(*I);
6809
6810 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006811 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006812 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006813 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006814
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006815
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006816 // Data for initializing _class_ro_t metaclass meta-data
6817 uint32_t flags = CLS_META;
6818 std::string InstanceSize;
6819 std::string InstanceStart;
6820
6821
6822 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6823 if (classIsHidden)
6824 flags |= OBJC2_CLS_HIDDEN;
6825
6826 if (!CDecl->getSuperClass())
6827 // class is root
6828 flags |= CLS_ROOT;
6829 InstanceSize = "sizeof(struct _class_t)";
6830 InstanceStart = InstanceSize;
6831 Write__class_ro_t_initializer(Context, Result, flags,
6832 InstanceStart, InstanceSize,
6833 ClassMethods,
6834 0,
6835 0,
6836 0,
6837 "_OBJC_METACLASS_RO_$_",
6838 CDecl->getNameAsString());
6839
6840
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006841 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006842 flags = CLS;
6843 if (classIsHidden)
6844 flags |= OBJC2_CLS_HIDDEN;
6845
6846 if (hasObjCExceptionAttribute(*Context, CDecl))
6847 flags |= CLS_EXCEPTION;
6848
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006849 if (!CDecl->getSuperClass())
6850 // class is root
6851 flags |= CLS_ROOT;
6852
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006853 InstanceSize.clear();
6854 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006855 if (!ObjCSynthesizedStructs.count(CDecl)) {
6856 InstanceSize = "0";
6857 InstanceStart = "0";
6858 }
6859 else {
6860 InstanceSize = "sizeof(struct ";
6861 InstanceSize += CDecl->getNameAsString();
6862 InstanceSize += "_IMPL)";
6863
6864 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6865 if (IVD) {
6866 InstanceStart += "__OFFSETOFIVAR__(struct ";
6867 InstanceStart += CDecl->getNameAsString();
6868 InstanceStart += "_IMPL, ";
6869 InstanceStart += IVD->getNameAsString();
6870 InstanceStart += ")";
6871 }
6872 else
6873 InstanceStart = InstanceSize;
6874 }
6875 Write__class_ro_t_initializer(Context, Result, flags,
6876 InstanceStart, InstanceSize,
6877 InstanceMethods,
6878 RefedProtocols,
6879 IVars,
6880 ClassProperties,
6881 "_OBJC_CLASS_RO_$_",
6882 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006883
6884 Write_class_t(Context, Result,
6885 "OBJC_METACLASS_$_",
6886 CDecl, /*metaclass*/true);
6887
6888 Write_class_t(Context, Result,
6889 "OBJC_CLASS_$_",
6890 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006891
6892 if (ImplementationIsNonLazy(IDecl))
6893 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006894
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006895}
6896
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006897void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6898 int ClsDefCount = ClassImplementation.size();
6899 if (!ClsDefCount)
6900 return;
6901 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6902 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6903 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6904 for (int i = 0; i < ClsDefCount; i++) {
6905 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6906 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6907 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6908 Result += CDecl->getName(); Result += ",\n";
6909 }
6910 Result += "};\n";
6911}
6912
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006913void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6914 int ClsDefCount = ClassImplementation.size();
6915 int CatDefCount = CategoryImplementation.size();
6916
6917 // For each implemented class, write out all its meta data.
6918 for (int i = 0; i < ClsDefCount; i++)
6919 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6920
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006921 RewriteClassSetupInitHook(Result);
6922
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006923 // For each implemented category, write out all its meta data.
6924 for (int i = 0; i < CatDefCount; i++)
6925 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6926
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006927 RewriteCategorySetupInitHook(Result);
6928
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006929 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006930 if (LangOpts.MicrosoftExt)
6931 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006932 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6933 Result += llvm::utostr(ClsDefCount); Result += "]";
6934 Result +=
6935 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6936 "regular,no_dead_strip\")))= {\n";
6937 for (int i = 0; i < ClsDefCount; i++) {
6938 Result += "\t&OBJC_CLASS_$_";
6939 Result += ClassImplementation[i]->getNameAsString();
6940 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006941 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006942 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006943
6944 if (!DefinedNonLazyClasses.empty()) {
6945 if (LangOpts.MicrosoftExt)
6946 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6947 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6948 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6949 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6950 Result += ",\n";
6951 }
6952 Result += "};\n";
6953 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006954 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006955
6956 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006957 if (LangOpts.MicrosoftExt)
6958 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006959 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6960 Result += llvm::utostr(CatDefCount); Result += "]";
6961 Result +=
6962 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6963 "regular,no_dead_strip\")))= {\n";
6964 for (int i = 0; i < CatDefCount; i++) {
6965 Result += "\t&_OBJC_$_CATEGORY_";
6966 Result +=
6967 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6968 Result += "_$_";
6969 Result += CategoryImplementation[i]->getNameAsString();
6970 Result += ",\n";
6971 }
6972 Result += "};\n";
6973 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006974
6975 if (!DefinedNonLazyCategories.empty()) {
6976 if (LangOpts.MicrosoftExt)
6977 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6978 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6979 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6980 Result += "\t&_OBJC_$_CATEGORY_";
6981 Result +=
6982 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6983 Result += "_$_";
6984 Result += DefinedNonLazyCategories[i]->getNameAsString();
6985 Result += ",\n";
6986 }
6987 Result += "};\n";
6988 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006989}
6990
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006991void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6992 if (LangOpts.MicrosoftExt)
6993 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6994
6995 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6996 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006997 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006998}
6999
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007000/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7001/// implementation.
7002void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7003 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007004 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007005 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7006 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007007 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007008 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7009 CDecl = CDecl->getNextClassCategory())
7010 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7011 break;
7012
7013 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007014 FullCategoryName += "_$_";
7015 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007016
7017 // Build _objc_method_list for class's instance methods if needed
7018 SmallVector<ObjCMethodDecl *, 32>
7019 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7020
7021 // If any of our property implementations have associated getters or
7022 // setters, produce metadata for them as well.
7023 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7024 PropEnd = IDecl->propimpl_end();
7025 Prop != PropEnd; ++Prop) {
7026 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7027 continue;
7028 if (!(*Prop)->getPropertyIvarDecl())
7029 continue;
7030 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
7031 if (!PD)
7032 continue;
7033 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7034 InstanceMethods.push_back(Getter);
7035 if (PD->isReadOnly())
7036 continue;
7037 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7038 InstanceMethods.push_back(Setter);
7039 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007040
Fariborz Jahanian61186122012-02-17 18:40:41 +00007041 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7042 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7043 FullCategoryName, true);
7044
7045 SmallVector<ObjCMethodDecl *, 32>
7046 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7047
7048 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7049 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7050 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007051
7052 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007053 // Protocol's super protocol list
7054 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007055 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7056 E = CDecl->protocol_end();
7057
7058 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007059 RefedProtocols.push_back(*I);
7060 // Must write out all protocol definitions in current qualifier list,
7061 // and in their nested qualifiers before writing out current definition.
7062 RewriteObjCProtocolMetaData(*I, Result);
7063 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007064
Fariborz Jahanian61186122012-02-17 18:40:41 +00007065 Write_protocol_list_initializer(Context, Result,
7066 RefedProtocols,
7067 "_OBJC_CATEGORY_PROTOCOLS_$_",
7068 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007069
Fariborz Jahanian61186122012-02-17 18:40:41 +00007070 // Protocol's property metadata.
7071 std::vector<ObjCPropertyDecl *> ClassProperties;
7072 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7073 E = CDecl->prop_end(); I != E; ++I)
7074 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007075
Fariborz Jahanian61186122012-02-17 18:40:41 +00007076 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7077 /* Container */0,
7078 "_OBJC_$_PROP_LIST_",
7079 FullCategoryName);
7080
7081 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007082 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007083 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007084 InstanceMethods,
7085 ClassMethods,
7086 RefedProtocols,
7087 ClassProperties);
7088
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007089 // Determine if this category is also "non-lazy".
7090 if (ImplementationIsNonLazy(IDecl))
7091 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007092
7093}
7094
7095void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7096 int CatDefCount = CategoryImplementation.size();
7097 if (!CatDefCount)
7098 return;
7099 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7100 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7101 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7102 for (int i = 0; i < CatDefCount; i++) {
7103 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7104 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7105 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7106 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7107 Result += ClassDecl->getName();
7108 Result += "_$_";
7109 Result += CatDecl->getName();
7110 Result += ",\n";
7111 }
7112 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007113}
7114
7115// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7116/// class methods.
7117template<typename MethodIterator>
7118void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7119 MethodIterator MethodEnd,
7120 bool IsInstanceMethod,
7121 StringRef prefix,
7122 StringRef ClassName,
7123 std::string &Result) {
7124 if (MethodBegin == MethodEnd) return;
7125
7126 if (!objc_impl_method) {
7127 /* struct _objc_method {
7128 SEL _cmd;
7129 char *method_types;
7130 void *_imp;
7131 }
7132 */
7133 Result += "\nstruct _objc_method {\n";
7134 Result += "\tSEL _cmd;\n";
7135 Result += "\tchar *method_types;\n";
7136 Result += "\tvoid *_imp;\n";
7137 Result += "};\n";
7138
7139 objc_impl_method = true;
7140 }
7141
7142 // Build _objc_method_list for class's methods if needed
7143
7144 /* struct {
7145 struct _objc_method_list *next_method;
7146 int method_count;
7147 struct _objc_method method_list[];
7148 }
7149 */
7150 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007151 Result += "\n";
7152 if (LangOpts.MicrosoftExt) {
7153 if (IsInstanceMethod)
7154 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7155 else
7156 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7157 }
7158 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007159 Result += "\tstruct _objc_method_list *next_method;\n";
7160 Result += "\tint method_count;\n";
7161 Result += "\tstruct _objc_method method_list[";
7162 Result += utostr(NumMethods);
7163 Result += "];\n} _OBJC_";
7164 Result += prefix;
7165 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7166 Result += "_METHODS_";
7167 Result += ClassName;
7168 Result += " __attribute__ ((used, section (\"__OBJC, __";
7169 Result += IsInstanceMethod ? "inst" : "cls";
7170 Result += "_meth\")))= ";
7171 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7172
7173 Result += "\t,{{(SEL)\"";
7174 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7175 std::string MethodTypeString;
7176 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7177 Result += "\", \"";
7178 Result += MethodTypeString;
7179 Result += "\", (void *)";
7180 Result += MethodInternalNames[*MethodBegin];
7181 Result += "}\n";
7182 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7183 Result += "\t ,{(SEL)\"";
7184 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7185 std::string MethodTypeString;
7186 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7187 Result += "\", \"";
7188 Result += MethodTypeString;
7189 Result += "\", (void *)";
7190 Result += MethodInternalNames[*MethodBegin];
7191 Result += "}\n";
7192 }
7193 Result += "\t }\n};\n";
7194}
7195
7196Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7197 SourceRange OldRange = IV->getSourceRange();
7198 Expr *BaseExpr = IV->getBase();
7199
7200 // Rewrite the base, but without actually doing replaces.
7201 {
7202 DisableReplaceStmtScope S(*this);
7203 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7204 IV->setBase(BaseExpr);
7205 }
7206
7207 ObjCIvarDecl *D = IV->getDecl();
7208
7209 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007210
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007211 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7212 const ObjCInterfaceType *iFaceDecl =
7213 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7214 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7215 // lookup which class implements the instance variable.
7216 ObjCInterfaceDecl *clsDeclared = 0;
7217 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7218 clsDeclared);
7219 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7220
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007221 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007222 std::string IvarOffsetName;
7223 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7224
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007225 ReferencedIvars[clsDeclared].insert(D);
7226
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007227 // cast offset to "char *".
7228 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7229 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007230 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007231 BaseExpr);
7232 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7233 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7234 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007235 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7236 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007237 SourceLocation());
7238 BinaryOperator *addExpr =
7239 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7240 Context->getPointerType(Context->CharTy),
7241 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007242 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007243 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7244 SourceLocation(),
7245 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007246 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007247 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007248 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007249
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007250 castExpr = NoTypeInfoCStyleCastExpr(Context,
7251 castT,
7252 CK_BitCast,
7253 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007254 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007255 VK_LValue, OK_Ordinary,
7256 SourceLocation());
7257 PE = new (Context) ParenExpr(OldRange.getBegin(),
7258 OldRange.getEnd(),
7259 Exp);
7260
7261 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007262 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007263
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007264 ReplaceStmtWithRange(IV, Replacement, OldRange);
7265 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007266}