blob: 4be7eb806f49455b5be753653dba7868975da966 [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.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001328 Expr *Base;
1329 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001330 {
1331 DisableReplaceStmtScope S(*this);
1332
1333 // Rebuild the base expression if we have one.
1334 Base = 0;
1335 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1336 Base = OldMsg->getInstanceReceiver();
1337 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1338 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1339 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001340
1341 unsigned numArgs = OldMsg->getNumArgs();
1342 for (unsigned i = 0; i < numArgs; i++) {
1343 Expr *Arg = OldMsg->getArg(i);
1344 if (isa<OpaqueValueExpr>(Arg))
1345 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1346 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1347 Args.push_back(Arg);
1348 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001349 }
1350
1351 // TODO: avoid this copy.
1352 SmallVector<SourceLocation, 1> SelLocs;
1353 OldMsg->getSelectorLocs(SelLocs);
1354
1355 ObjCMessageExpr *NewMsg = 0;
1356 switch (OldMsg->getReceiverKind()) {
1357 case ObjCMessageExpr::Class:
1358 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1359 OldMsg->getValueKind(),
1360 OldMsg->getLeftLoc(),
1361 OldMsg->getClassReceiverTypeInfo(),
1362 OldMsg->getSelector(),
1363 SelLocs,
1364 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001365 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001366 OldMsg->getRightLoc(),
1367 OldMsg->isImplicit());
1368 break;
1369
1370 case ObjCMessageExpr::Instance:
1371 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1372 OldMsg->getValueKind(),
1373 OldMsg->getLeftLoc(),
1374 Base,
1375 OldMsg->getSelector(),
1376 SelLocs,
1377 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001378 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001379 OldMsg->getRightLoc(),
1380 OldMsg->isImplicit());
1381 break;
1382
1383 case ObjCMessageExpr::SuperClass:
1384 case ObjCMessageExpr::SuperInstance:
1385 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1386 OldMsg->getValueKind(),
1387 OldMsg->getLeftLoc(),
1388 OldMsg->getSuperLoc(),
1389 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1390 OldMsg->getSuperType(),
1391 OldMsg->getSelector(),
1392 SelLocs,
1393 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001394 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001395 OldMsg->getRightLoc(),
1396 OldMsg->isImplicit());
1397 break;
1398 }
1399
1400 Stmt *Replacement = SynthMessageExpr(NewMsg);
1401 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1402 return Replacement;
1403}
1404
1405Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1406 SourceRange OldRange = PseudoOp->getSourceRange();
1407
1408 // We just magically know some things about the structure of this
1409 // expression.
1410 ObjCMessageExpr *OldMsg =
1411 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1412
1413 // Because the rewriter doesn't allow us to rewrite rewritten code,
1414 // we need to suppress rewriting the sub-statements.
1415 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001416 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001417 {
1418 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001419 // Rebuild the base expression if we have one.
1420 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1421 Base = OldMsg->getInstanceReceiver();
1422 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1423 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1424 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001425 unsigned numArgs = OldMsg->getNumArgs();
1426 for (unsigned i = 0; i < numArgs; i++) {
1427 Expr *Arg = OldMsg->getArg(i);
1428 if (isa<OpaqueValueExpr>(Arg))
1429 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1430 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1431 Args.push_back(Arg);
1432 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001433 }
1434
1435 // Intentionally empty.
1436 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001437
1438 ObjCMessageExpr *NewMsg = 0;
1439 switch (OldMsg->getReceiverKind()) {
1440 case ObjCMessageExpr::Class:
1441 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1442 OldMsg->getValueKind(),
1443 OldMsg->getLeftLoc(),
1444 OldMsg->getClassReceiverTypeInfo(),
1445 OldMsg->getSelector(),
1446 SelLocs,
1447 OldMsg->getMethodDecl(),
1448 Args,
1449 OldMsg->getRightLoc(),
1450 OldMsg->isImplicit());
1451 break;
1452
1453 case ObjCMessageExpr::Instance:
1454 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1455 OldMsg->getValueKind(),
1456 OldMsg->getLeftLoc(),
1457 Base,
1458 OldMsg->getSelector(),
1459 SelLocs,
1460 OldMsg->getMethodDecl(),
1461 Args,
1462 OldMsg->getRightLoc(),
1463 OldMsg->isImplicit());
1464 break;
1465
1466 case ObjCMessageExpr::SuperClass:
1467 case ObjCMessageExpr::SuperInstance:
1468 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1469 OldMsg->getValueKind(),
1470 OldMsg->getLeftLoc(),
1471 OldMsg->getSuperLoc(),
1472 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1473 OldMsg->getSuperType(),
1474 OldMsg->getSelector(),
1475 SelLocs,
1476 OldMsg->getMethodDecl(),
1477 Args,
1478 OldMsg->getRightLoc(),
1479 OldMsg->isImplicit());
1480 break;
1481 }
1482
1483 Stmt *Replacement = SynthMessageExpr(NewMsg);
1484 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1485 return Replacement;
1486}
1487
1488/// SynthCountByEnumWithState - To print:
1489/// ((unsigned int (*)
1490/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1491/// (void *)objc_msgSend)((id)l_collection,
1492/// sel_registerName(
1493/// "countByEnumeratingWithState:objects:count:"),
1494/// &enumState,
1495/// (id *)__rw_items, (unsigned int)16)
1496///
1497void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1498 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1499 "id *, unsigned int))(void *)objc_msgSend)";
1500 buf += "\n\t\t";
1501 buf += "((id)l_collection,\n\t\t";
1502 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1503 buf += "\n\t\t";
1504 buf += "&enumState, "
1505 "(id *)__rw_items, (unsigned int)16)";
1506}
1507
1508/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1509/// statement to exit to its outer synthesized loop.
1510///
1511Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1512 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1513 return S;
1514 // replace break with goto __break_label
1515 std::string buf;
1516
1517 SourceLocation startLoc = S->getLocStart();
1518 buf = "goto __break_label_";
1519 buf += utostr(ObjCBcLabelNo.back());
1520 ReplaceText(startLoc, strlen("break"), buf);
1521
1522 return 0;
1523}
1524
1525/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1526/// statement to continue with its inner synthesized loop.
1527///
1528Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1529 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1530 return S;
1531 // replace continue with goto __continue_label
1532 std::string buf;
1533
1534 SourceLocation startLoc = S->getLocStart();
1535 buf = "goto __continue_label_";
1536 buf += utostr(ObjCBcLabelNo.back());
1537 ReplaceText(startLoc, strlen("continue"), buf);
1538
1539 return 0;
1540}
1541
1542/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1543/// It rewrites:
1544/// for ( type elem in collection) { stmts; }
1545
1546/// Into:
1547/// {
1548/// type elem;
1549/// struct __objcFastEnumerationState enumState = { 0 };
1550/// id __rw_items[16];
1551/// id l_collection = (id)collection;
1552/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1553/// objects:__rw_items count:16];
1554/// if (limit) {
1555/// unsigned long startMutations = *enumState.mutationsPtr;
1556/// do {
1557/// unsigned long counter = 0;
1558/// do {
1559/// if (startMutations != *enumState.mutationsPtr)
1560/// objc_enumerationMutation(l_collection);
1561/// elem = (type)enumState.itemsPtr[counter++];
1562/// stmts;
1563/// __continue_label: ;
1564/// } while (counter < limit);
1565/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1566/// objects:__rw_items count:16]);
1567/// elem = nil;
1568/// __break_label: ;
1569/// }
1570/// else
1571/// elem = nil;
1572/// }
1573///
1574Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1575 SourceLocation OrigEnd) {
1576 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1577 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1578 "ObjCForCollectionStmt Statement stack mismatch");
1579 assert(!ObjCBcLabelNo.empty() &&
1580 "ObjCForCollectionStmt - Label No stack empty");
1581
1582 SourceLocation startLoc = S->getLocStart();
1583 const char *startBuf = SM->getCharacterData(startLoc);
1584 StringRef elementName;
1585 std::string elementTypeAsString;
1586 std::string buf;
1587 buf = "\n{\n\t";
1588 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1589 // type elem;
1590 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1591 QualType ElementType = cast<ValueDecl>(D)->getType();
1592 if (ElementType->isObjCQualifiedIdType() ||
1593 ElementType->isObjCQualifiedInterfaceType())
1594 // Simply use 'id' for all qualified types.
1595 elementTypeAsString = "id";
1596 else
1597 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1598 buf += elementTypeAsString;
1599 buf += " ";
1600 elementName = D->getName();
1601 buf += elementName;
1602 buf += ";\n\t";
1603 }
1604 else {
1605 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1606 elementName = DR->getDecl()->getName();
1607 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1608 if (VD->getType()->isObjCQualifiedIdType() ||
1609 VD->getType()->isObjCQualifiedInterfaceType())
1610 // Simply use 'id' for all qualified types.
1611 elementTypeAsString = "id";
1612 else
1613 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1614 }
1615
1616 // struct __objcFastEnumerationState enumState = { 0 };
1617 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1618 // id __rw_items[16];
1619 buf += "id __rw_items[16];\n\t";
1620 // id l_collection = (id)
1621 buf += "id l_collection = (id)";
1622 // Find start location of 'collection' the hard way!
1623 const char *startCollectionBuf = startBuf;
1624 startCollectionBuf += 3; // skip 'for'
1625 startCollectionBuf = strchr(startCollectionBuf, '(');
1626 startCollectionBuf++; // skip '('
1627 // find 'in' and skip it.
1628 while (*startCollectionBuf != ' ' ||
1629 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1630 (*(startCollectionBuf+3) != ' ' &&
1631 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1632 startCollectionBuf++;
1633 startCollectionBuf += 3;
1634
1635 // Replace: "for (type element in" with string constructed thus far.
1636 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1637 // Replace ')' in for '(' type elem in collection ')' with ';'
1638 SourceLocation rightParenLoc = S->getRParenLoc();
1639 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1640 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1641 buf = ";\n\t";
1642
1643 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1644 // objects:__rw_items count:16];
1645 // which is synthesized into:
1646 // unsigned int limit =
1647 // ((unsigned int (*)
1648 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1649 // (void *)objc_msgSend)((id)l_collection,
1650 // sel_registerName(
1651 // "countByEnumeratingWithState:objects:count:"),
1652 // (struct __objcFastEnumerationState *)&state,
1653 // (id *)__rw_items, (unsigned int)16);
1654 buf += "unsigned long limit =\n\t\t";
1655 SynthCountByEnumWithState(buf);
1656 buf += ";\n\t";
1657 /// if (limit) {
1658 /// unsigned long startMutations = *enumState.mutationsPtr;
1659 /// do {
1660 /// unsigned long counter = 0;
1661 /// do {
1662 /// if (startMutations != *enumState.mutationsPtr)
1663 /// objc_enumerationMutation(l_collection);
1664 /// elem = (type)enumState.itemsPtr[counter++];
1665 buf += "if (limit) {\n\t";
1666 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1667 buf += "do {\n\t\t";
1668 buf += "unsigned long counter = 0;\n\t\t";
1669 buf += "do {\n\t\t\t";
1670 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1671 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1672 buf += elementName;
1673 buf += " = (";
1674 buf += elementTypeAsString;
1675 buf += ")enumState.itemsPtr[counter++];";
1676 // Replace ')' in for '(' type elem in collection ')' with all of these.
1677 ReplaceText(lparenLoc, 1, buf);
1678
1679 /// __continue_label: ;
1680 /// } while (counter < limit);
1681 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1682 /// objects:__rw_items count:16]);
1683 /// elem = nil;
1684 /// __break_label: ;
1685 /// }
1686 /// else
1687 /// elem = nil;
1688 /// }
1689 ///
1690 buf = ";\n\t";
1691 buf += "__continue_label_";
1692 buf += utostr(ObjCBcLabelNo.back());
1693 buf += ": ;";
1694 buf += "\n\t\t";
1695 buf += "} while (counter < limit);\n\t";
1696 buf += "} while (limit = ";
1697 SynthCountByEnumWithState(buf);
1698 buf += ");\n\t";
1699 buf += elementName;
1700 buf += " = ((";
1701 buf += elementTypeAsString;
1702 buf += ")0);\n\t";
1703 buf += "__break_label_";
1704 buf += utostr(ObjCBcLabelNo.back());
1705 buf += ": ;\n\t";
1706 buf += "}\n\t";
1707 buf += "else\n\t\t";
1708 buf += elementName;
1709 buf += " = ((";
1710 buf += elementTypeAsString;
1711 buf += ")0);\n\t";
1712 buf += "}\n";
1713
1714 // Insert all these *after* the statement body.
1715 // FIXME: If this should support Obj-C++, support CXXTryStmt
1716 if (isa<CompoundStmt>(S->getBody())) {
1717 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1718 InsertText(endBodyLoc, buf);
1719 } else {
1720 /* Need to treat single statements specially. For example:
1721 *
1722 * for (A *a in b) if (stuff()) break;
1723 * for (A *a in b) xxxyy;
1724 *
1725 * The following code simply scans ahead to the semi to find the actual end.
1726 */
1727 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1728 const char *semiBuf = strchr(stmtBuf, ';');
1729 assert(semiBuf && "Can't find ';'");
1730 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1731 InsertText(endBodyLoc, buf);
1732 }
1733 Stmts.pop_back();
1734 ObjCBcLabelNo.pop_back();
1735 return 0;
1736}
1737
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001738static void Write_RethrowObject(std::string &buf) {
1739 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1740 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1741 buf += "\tid rethrow;\n";
1742 buf += "\t} _fin_force_rethow(_rethrow);";
1743}
1744
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001745/// RewriteObjCSynchronizedStmt -
1746/// This routine rewrites @synchronized(expr) stmt;
1747/// into:
1748/// objc_sync_enter(expr);
1749/// @try stmt @finally { objc_sync_exit(expr); }
1750///
1751Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1752 // Get the start location and compute the semi location.
1753 SourceLocation startLoc = S->getLocStart();
1754 const char *startBuf = SM->getCharacterData(startLoc);
1755
1756 assert((*startBuf == '@') && "bogus @synchronized location");
1757
1758 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001759 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001760
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001761 const char *lparenBuf = startBuf;
1762 while (*lparenBuf != '(') lparenBuf++;
1763 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001764
1765 buf = "; objc_sync_enter(_sync_obj);\n";
1766 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1767 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1768 buf += "\n\tid sync_exit;";
1769 buf += "\n\t} _sync_exit(_sync_obj);\n";
1770
1771 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1772 // the sync expression is typically a message expression that's already
1773 // been rewritten! (which implies the SourceLocation's are invalid).
1774 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1775 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1776 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1777 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1778
1779 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1780 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1781 assert (*LBraceLocBuf == '{');
1782 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001783
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001784 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001785 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1786 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001787
1788 buf = "} catch (id e) {_rethrow = e;}\n";
1789 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001790 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001791 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001792
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001793 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001794
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001795 return 0;
1796}
1797
1798void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1799{
1800 // Perform a bottom up traversal of all children.
1801 for (Stmt::child_range CI = S->children(); CI; ++CI)
1802 if (*CI)
1803 WarnAboutReturnGotoStmts(*CI);
1804
1805 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1806 Diags.Report(Context->getFullLoc(S->getLocStart()),
1807 TryFinallyContainsReturnDiag);
1808 }
1809 return;
1810}
1811
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001812Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001813 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001814 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001815 std::string buf;
1816
1817 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001818 if (noCatch)
1819 buf = "{ id volatile _rethrow = 0;\n";
1820 else {
1821 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1822 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001823 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001824 // Get the start location and compute the semi location.
1825 SourceLocation startLoc = S->getLocStart();
1826 const char *startBuf = SM->getCharacterData(startLoc);
1827
1828 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001829 if (finalStmt)
1830 ReplaceText(startLoc, 1, buf);
1831 else
1832 // @try -> try
1833 ReplaceText(startLoc, 1, "");
1834
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001835 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1836 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001837 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001838
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001839 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001840 bool AtRemoved = false;
1841 if (catchDecl) {
1842 QualType t = catchDecl->getType();
1843 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1844 // Should be a pointer to a class.
1845 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1846 if (IDecl) {
1847 std::string Result;
1848 startBuf = SM->getCharacterData(startLoc);
1849 assert((*startBuf == '@') && "bogus @catch location");
1850 SourceLocation rParenLoc = Catch->getRParenLoc();
1851 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1852
1853 // _objc_exc_Foo *_e as argument to catch.
1854 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1855 Result += " *_"; Result += catchDecl->getNameAsString();
1856 Result += ")";
1857 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1858 // Foo *e = (Foo *)_e;
1859 Result.clear();
1860 Result = "{ ";
1861 Result += IDecl->getNameAsString();
1862 Result += " *"; Result += catchDecl->getNameAsString();
1863 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1864 Result += "_"; Result += catchDecl->getNameAsString();
1865
1866 Result += "; ";
1867 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1868 ReplaceText(lBraceLoc, 1, Result);
1869 AtRemoved = true;
1870 }
1871 }
1872 }
1873 if (!AtRemoved)
1874 // @catch -> catch
1875 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001876
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001877 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001878 if (finalStmt) {
1879 buf.clear();
1880 if (noCatch)
1881 buf = "catch (id e) {_rethrow = e;}\n";
1882 else
1883 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1884
1885 SourceLocation startFinalLoc = finalStmt->getLocStart();
1886 ReplaceText(startFinalLoc, 8, buf);
1887 Stmt *body = finalStmt->getFinallyBody();
1888 SourceLocation startFinalBodyLoc = body->getLocStart();
1889 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001890 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001891 ReplaceText(startFinalBodyLoc, 1, buf);
1892
1893 SourceLocation endFinalBodyLoc = body->getLocEnd();
1894 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001895 // Now check for any return/continue/go statements within the @try.
1896 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001897 }
1898
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001899 return 0;
1900}
1901
1902// This can't be done with ReplaceStmt(S, ThrowExpr), since
1903// the throw expression is typically a message expression that's already
1904// been rewritten! (which implies the SourceLocation's are invalid).
1905Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1906 // Get the start location and compute the semi location.
1907 SourceLocation startLoc = S->getLocStart();
1908 const char *startBuf = SM->getCharacterData(startLoc);
1909
1910 assert((*startBuf == '@') && "bogus @throw location");
1911
1912 std::string buf;
1913 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1914 if (S->getThrowExpr())
1915 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001916 else
1917 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001918
1919 // handle "@ throw" correctly.
1920 const char *wBuf = strchr(startBuf, 'w');
1921 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1922 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1923
1924 const char *semiBuf = strchr(startBuf, ';');
1925 assert((*semiBuf == ';') && "@throw: can't find ';'");
1926 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001927 if (S->getThrowExpr())
1928 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001929 return 0;
1930}
1931
1932Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1933 // Create a new string expression.
1934 QualType StrType = Context->getPointerType(Context->CharTy);
1935 std::string StrEncoding;
1936 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1937 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1938 StringLiteral::Ascii, false,
1939 StrType, SourceLocation());
1940 ReplaceStmt(Exp, Replacement);
1941
1942 // Replace this subexpr in the parent.
1943 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1944 return Replacement;
1945}
1946
1947Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1948 if (!SelGetUidFunctionDecl)
1949 SynthSelGetUidFunctionDecl();
1950 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1951 // Create a call to sel_registerName("selName").
1952 SmallVector<Expr*, 8> SelExprs;
1953 QualType argType = Context->getPointerType(Context->CharTy);
1954 SelExprs.push_back(StringLiteral::Create(*Context,
1955 Exp->getSelector().getAsString(),
1956 StringLiteral::Ascii, false,
1957 argType, SourceLocation()));
1958 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1959 &SelExprs[0], SelExprs.size());
1960 ReplaceStmt(Exp, SelExp);
1961 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1962 return SelExp;
1963}
1964
1965CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1966 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1967 SourceLocation EndLoc) {
1968 // Get the type, we will need to reference it in a couple spots.
1969 QualType msgSendType = FD->getType();
1970
1971 // Create a reference to the objc_msgSend() declaration.
1972 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001973 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001974
1975 // Now, we cast the reference to a pointer to the objc_msgSend type.
1976 QualType pToFunc = Context->getPointerType(msgSendType);
1977 ImplicitCastExpr *ICE =
1978 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1979 DRE, 0, VK_RValue);
1980
1981 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1982
1983 CallExpr *Exp =
1984 new (Context) CallExpr(*Context, ICE, args, nargs,
1985 FT->getCallResultType(*Context),
1986 VK_RValue, EndLoc);
1987 return Exp;
1988}
1989
1990static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1991 const char *&startRef, const char *&endRef) {
1992 while (startBuf < endBuf) {
1993 if (*startBuf == '<')
1994 startRef = startBuf; // mark the start.
1995 if (*startBuf == '>') {
1996 if (startRef && *startRef == '<') {
1997 endRef = startBuf; // mark the end.
1998 return true;
1999 }
2000 return false;
2001 }
2002 startBuf++;
2003 }
2004 return false;
2005}
2006
2007static void scanToNextArgument(const char *&argRef) {
2008 int angle = 0;
2009 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2010 if (*argRef == '<')
2011 angle++;
2012 else if (*argRef == '>')
2013 angle--;
2014 argRef++;
2015 }
2016 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2017}
2018
2019bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2020 if (T->isObjCQualifiedIdType())
2021 return true;
2022 if (const PointerType *PT = T->getAs<PointerType>()) {
2023 if (PT->getPointeeType()->isObjCQualifiedIdType())
2024 return true;
2025 }
2026 if (T->isObjCObjectPointerType()) {
2027 T = T->getPointeeType();
2028 return T->isObjCQualifiedInterfaceType();
2029 }
2030 if (T->isArrayType()) {
2031 QualType ElemTy = Context->getBaseElementType(T);
2032 return needToScanForQualifiers(ElemTy);
2033 }
2034 return false;
2035}
2036
2037void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2038 QualType Type = E->getType();
2039 if (needToScanForQualifiers(Type)) {
2040 SourceLocation Loc, EndLoc;
2041
2042 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2043 Loc = ECE->getLParenLoc();
2044 EndLoc = ECE->getRParenLoc();
2045 } else {
2046 Loc = E->getLocStart();
2047 EndLoc = E->getLocEnd();
2048 }
2049 // This will defend against trying to rewrite synthesized expressions.
2050 if (Loc.isInvalid() || EndLoc.isInvalid())
2051 return;
2052
2053 const char *startBuf = SM->getCharacterData(Loc);
2054 const char *endBuf = SM->getCharacterData(EndLoc);
2055 const char *startRef = 0, *endRef = 0;
2056 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2057 // Get the locations of the startRef, endRef.
2058 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2059 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2060 // Comment out the protocol references.
2061 InsertText(LessLoc, "/*");
2062 InsertText(GreaterLoc, "*/");
2063 }
2064 }
2065}
2066
2067void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2068 SourceLocation Loc;
2069 QualType Type;
2070 const FunctionProtoType *proto = 0;
2071 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2072 Loc = VD->getLocation();
2073 Type = VD->getType();
2074 }
2075 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2076 Loc = FD->getLocation();
2077 // Check for ObjC 'id' and class types that have been adorned with protocol
2078 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2079 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2080 assert(funcType && "missing function type");
2081 proto = dyn_cast<FunctionProtoType>(funcType);
2082 if (!proto)
2083 return;
2084 Type = proto->getResultType();
2085 }
2086 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2087 Loc = FD->getLocation();
2088 Type = FD->getType();
2089 }
2090 else
2091 return;
2092
2093 if (needToScanForQualifiers(Type)) {
2094 // Since types are unique, we need to scan the buffer.
2095
2096 const char *endBuf = SM->getCharacterData(Loc);
2097 const char *startBuf = endBuf;
2098 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2099 startBuf--; // scan backward (from the decl location) for return type.
2100 const char *startRef = 0, *endRef = 0;
2101 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2102 // Get the locations of the startRef, endRef.
2103 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2104 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2105 // Comment out the protocol references.
2106 InsertText(LessLoc, "/*");
2107 InsertText(GreaterLoc, "*/");
2108 }
2109 }
2110 if (!proto)
2111 return; // most likely, was a variable
2112 // Now check arguments.
2113 const char *startBuf = SM->getCharacterData(Loc);
2114 const char *startFuncBuf = startBuf;
2115 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2116 if (needToScanForQualifiers(proto->getArgType(i))) {
2117 // Since types are unique, we need to scan the buffer.
2118
2119 const char *endBuf = startBuf;
2120 // scan forward (from the decl location) for argument types.
2121 scanToNextArgument(endBuf);
2122 const char *startRef = 0, *endRef = 0;
2123 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2124 // Get the locations of the startRef, endRef.
2125 SourceLocation LessLoc =
2126 Loc.getLocWithOffset(startRef-startFuncBuf);
2127 SourceLocation GreaterLoc =
2128 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2129 // Comment out the protocol references.
2130 InsertText(LessLoc, "/*");
2131 InsertText(GreaterLoc, "*/");
2132 }
2133 startBuf = ++endBuf;
2134 }
2135 else {
2136 // If the function name is derived from a macro expansion, then the
2137 // argument buffer will not follow the name. Need to speak with Chris.
2138 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2139 startBuf++; // scan forward (from the decl location) for argument types.
2140 startBuf++;
2141 }
2142 }
2143}
2144
2145void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2146 QualType QT = ND->getType();
2147 const Type* TypePtr = QT->getAs<Type>();
2148 if (!isa<TypeOfExprType>(TypePtr))
2149 return;
2150 while (isa<TypeOfExprType>(TypePtr)) {
2151 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2152 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2153 TypePtr = QT->getAs<Type>();
2154 }
2155 // FIXME. This will not work for multiple declarators; as in:
2156 // __typeof__(a) b,c,d;
2157 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2158 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2159 const char *startBuf = SM->getCharacterData(DeclLoc);
2160 if (ND->getInit()) {
2161 std::string Name(ND->getNameAsString());
2162 TypeAsString += " " + Name + " = ";
2163 Expr *E = ND->getInit();
2164 SourceLocation startLoc;
2165 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2166 startLoc = ECE->getLParenLoc();
2167 else
2168 startLoc = E->getLocStart();
2169 startLoc = SM->getExpansionLoc(startLoc);
2170 const char *endBuf = SM->getCharacterData(startLoc);
2171 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2172 }
2173 else {
2174 SourceLocation X = ND->getLocEnd();
2175 X = SM->getExpansionLoc(X);
2176 const char *endBuf = SM->getCharacterData(X);
2177 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2178 }
2179}
2180
2181// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2182void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2183 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2184 SmallVector<QualType, 16> ArgTys;
2185 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2186 QualType getFuncType =
2187 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2188 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2189 SourceLocation(),
2190 SourceLocation(),
2191 SelGetUidIdent, getFuncType, 0,
2192 SC_Extern,
2193 SC_None, false);
2194}
2195
2196void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2197 // declared in <objc/objc.h>
2198 if (FD->getIdentifier() &&
2199 FD->getName() == "sel_registerName") {
2200 SelGetUidFunctionDecl = FD;
2201 return;
2202 }
2203 RewriteObjCQualifiedInterfaceTypes(FD);
2204}
2205
2206void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2207 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2208 const char *argPtr = TypeString.c_str();
2209 if (!strchr(argPtr, '^')) {
2210 Str += TypeString;
2211 return;
2212 }
2213 while (*argPtr) {
2214 Str += (*argPtr == '^' ? '*' : *argPtr);
2215 argPtr++;
2216 }
2217}
2218
2219// FIXME. Consolidate this routine with RewriteBlockPointerType.
2220void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2221 ValueDecl *VD) {
2222 QualType Type = VD->getType();
2223 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2224 const char *argPtr = TypeString.c_str();
2225 int paren = 0;
2226 while (*argPtr) {
2227 switch (*argPtr) {
2228 case '(':
2229 Str += *argPtr;
2230 paren++;
2231 break;
2232 case ')':
2233 Str += *argPtr;
2234 paren--;
2235 break;
2236 case '^':
2237 Str += '*';
2238 if (paren == 1)
2239 Str += VD->getNameAsString();
2240 break;
2241 default:
2242 Str += *argPtr;
2243 break;
2244 }
2245 argPtr++;
2246 }
2247}
2248
2249
2250void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2251 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2252 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2253 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2254 if (!proto)
2255 return;
2256 QualType Type = proto->getResultType();
2257 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2258 FdStr += " ";
2259 FdStr += FD->getName();
2260 FdStr += "(";
2261 unsigned numArgs = proto->getNumArgs();
2262 for (unsigned i = 0; i < numArgs; i++) {
2263 QualType ArgType = proto->getArgType(i);
2264 RewriteBlockPointerType(FdStr, ArgType);
2265 if (i+1 < numArgs)
2266 FdStr += ", ";
2267 }
2268 FdStr += ");\n";
2269 InsertText(FunLocStart, FdStr);
2270 CurFunctionDeclToDeclareForBlock = 0;
2271}
2272
2273// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2274void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2275 if (SuperContructorFunctionDecl)
2276 return;
2277 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2278 SmallVector<QualType, 16> ArgTys;
2279 QualType argT = Context->getObjCIdType();
2280 assert(!argT.isNull() && "Can't find 'id' type");
2281 ArgTys.push_back(argT);
2282 ArgTys.push_back(argT);
2283 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2284 &ArgTys[0], ArgTys.size());
2285 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2286 SourceLocation(),
2287 SourceLocation(),
2288 msgSendIdent, msgSendType, 0,
2289 SC_Extern,
2290 SC_None, false);
2291}
2292
2293// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2294void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2295 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2296 SmallVector<QualType, 16> ArgTys;
2297 QualType argT = Context->getObjCIdType();
2298 assert(!argT.isNull() && "Can't find 'id' type");
2299 ArgTys.push_back(argT);
2300 argT = Context->getObjCSelType();
2301 assert(!argT.isNull() && "Can't find 'SEL' type");
2302 ArgTys.push_back(argT);
2303 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2304 &ArgTys[0], ArgTys.size(),
2305 true /*isVariadic*/);
2306 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2307 SourceLocation(),
2308 SourceLocation(),
2309 msgSendIdent, msgSendType, 0,
2310 SC_Extern,
2311 SC_None, false);
2312}
2313
2314// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2315void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2316 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2317 SmallVector<QualType, 16> ArgTys;
2318 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2319 SourceLocation(), SourceLocation(),
2320 &Context->Idents.get("objc_super"));
2321 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2322 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2323 ArgTys.push_back(argT);
2324 argT = Context->getObjCSelType();
2325 assert(!argT.isNull() && "Can't find 'SEL' type");
2326 ArgTys.push_back(argT);
2327 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2328 &ArgTys[0], ArgTys.size(),
2329 true /*isVariadic*/);
2330 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2331 SourceLocation(),
2332 SourceLocation(),
2333 msgSendIdent, msgSendType, 0,
2334 SC_Extern,
2335 SC_None, false);
2336}
2337
2338// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2339void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2340 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2341 SmallVector<QualType, 16> ArgTys;
2342 QualType argT = Context->getObjCIdType();
2343 assert(!argT.isNull() && "Can't find 'id' type");
2344 ArgTys.push_back(argT);
2345 argT = Context->getObjCSelType();
2346 assert(!argT.isNull() && "Can't find 'SEL' type");
2347 ArgTys.push_back(argT);
2348 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2349 &ArgTys[0], ArgTys.size(),
2350 true /*isVariadic*/);
2351 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2352 SourceLocation(),
2353 SourceLocation(),
2354 msgSendIdent, msgSendType, 0,
2355 SC_Extern,
2356 SC_None, false);
2357}
2358
2359// SynthMsgSendSuperStretFunctionDecl -
2360// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2361void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2362 IdentifierInfo *msgSendIdent =
2363 &Context->Idents.get("objc_msgSendSuper_stret");
2364 SmallVector<QualType, 16> ArgTys;
2365 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2366 SourceLocation(), SourceLocation(),
2367 &Context->Idents.get("objc_super"));
2368 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2369 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2370 ArgTys.push_back(argT);
2371 argT = Context->getObjCSelType();
2372 assert(!argT.isNull() && "Can't find 'SEL' type");
2373 ArgTys.push_back(argT);
2374 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2375 &ArgTys[0], ArgTys.size(),
2376 true /*isVariadic*/);
2377 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2378 SourceLocation(),
2379 SourceLocation(),
2380 msgSendIdent, msgSendType, 0,
2381 SC_Extern,
2382 SC_None, false);
2383}
2384
2385// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2386void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2387 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2388 SmallVector<QualType, 16> ArgTys;
2389 QualType argT = Context->getObjCIdType();
2390 assert(!argT.isNull() && "Can't find 'id' type");
2391 ArgTys.push_back(argT);
2392 argT = Context->getObjCSelType();
2393 assert(!argT.isNull() && "Can't find 'SEL' type");
2394 ArgTys.push_back(argT);
2395 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2396 &ArgTys[0], ArgTys.size(),
2397 true /*isVariadic*/);
2398 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2399 SourceLocation(),
2400 SourceLocation(),
2401 msgSendIdent, msgSendType, 0,
2402 SC_Extern,
2403 SC_None, false);
2404}
2405
2406// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2407void RewriteModernObjC::SynthGetClassFunctionDecl() {
2408 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2409 SmallVector<QualType, 16> ArgTys;
2410 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2411 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2412 &ArgTys[0], ArgTys.size());
2413 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2414 SourceLocation(),
2415 SourceLocation(),
2416 getClassIdent, getClassType, 0,
2417 SC_Extern,
2418 SC_None, false);
2419}
2420
2421// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2422void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2423 IdentifierInfo *getSuperClassIdent =
2424 &Context->Idents.get("class_getSuperclass");
2425 SmallVector<QualType, 16> ArgTys;
2426 ArgTys.push_back(Context->getObjCClassType());
2427 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2428 &ArgTys[0], ArgTys.size());
2429 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2430 SourceLocation(),
2431 SourceLocation(),
2432 getSuperClassIdent,
2433 getClassType, 0,
2434 SC_Extern,
2435 SC_None,
2436 false);
2437}
2438
2439// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2440void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2441 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2442 SmallVector<QualType, 16> ArgTys;
2443 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2444 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2445 &ArgTys[0], ArgTys.size());
2446 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2447 SourceLocation(),
2448 SourceLocation(),
2449 getClassIdent, getClassType, 0,
2450 SC_Extern,
2451 SC_None, false);
2452}
2453
2454Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2455 QualType strType = getConstantStringStructType();
2456
2457 std::string S = "__NSConstantStringImpl_";
2458
2459 std::string tmpName = InFileName;
2460 unsigned i;
2461 for (i=0; i < tmpName.length(); i++) {
2462 char c = tmpName.at(i);
2463 // replace any non alphanumeric characters with '_'.
2464 if (!isalpha(c) && (c < '0' || c > '9'))
2465 tmpName[i] = '_';
2466 }
2467 S += tmpName;
2468 S += "_";
2469 S += utostr(NumObjCStringLiterals++);
2470
2471 Preamble += "static __NSConstantStringImpl " + S;
2472 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2473 Preamble += "0x000007c8,"; // utf8_str
2474 // The pretty printer for StringLiteral handles escape characters properly.
2475 std::string prettyBufS;
2476 llvm::raw_string_ostream prettyBuf(prettyBufS);
2477 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2478 PrintingPolicy(LangOpts));
2479 Preamble += prettyBuf.str();
2480 Preamble += ",";
2481 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2482
2483 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2484 SourceLocation(), &Context->Idents.get(S),
2485 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002486 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002487 SourceLocation());
2488 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2489 Context->getPointerType(DRE->getType()),
2490 VK_RValue, OK_Ordinary,
2491 SourceLocation());
2492 // cast to NSConstantString *
2493 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2494 CK_CPointerToObjCPointerCast, Unop);
2495 ReplaceStmt(Exp, cast);
2496 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2497 return cast;
2498}
2499
Fariborz Jahanian55947042012-03-27 20:17:30 +00002500Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2501 unsigned IntSize =
2502 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2503
2504 Expr *FlagExp = IntegerLiteral::Create(*Context,
2505 llvm::APInt(IntSize, Exp->getValue()),
2506 Context->IntTy, Exp->getLocation());
2507 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2508 CK_BitCast, FlagExp);
2509 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2510 cast);
2511 ReplaceStmt(Exp, PE);
2512 return PE;
2513}
2514
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002515Stmt *RewriteModernObjC::RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp) {
2516 // synthesize declaration of helper functions needed in this routine.
2517 if (!SelGetUidFunctionDecl)
2518 SynthSelGetUidFunctionDecl();
2519 // use objc_msgSend() for all.
2520 if (!MsgSendFunctionDecl)
2521 SynthMsgSendFunctionDecl();
2522 if (!GetClassFunctionDecl)
2523 SynthGetClassFunctionDecl();
2524
2525 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2526 SourceLocation StartLoc = Exp->getLocStart();
2527 SourceLocation EndLoc = Exp->getLocEnd();
2528
2529 // Synthesize a call to objc_msgSend().
2530 SmallVector<Expr*, 4> MsgExprs;
2531 SmallVector<Expr*, 4> ClsExprs;
2532 QualType argType = Context->getPointerType(Context->CharTy);
2533 QualType expType = Exp->getType();
2534
2535 // Create a call to objc_getClass("NSNumber"). It will be th 1st argument.
2536 ObjCInterfaceDecl *Class =
2537 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2538
2539 IdentifierInfo *clsName = Class->getIdentifier();
2540 ClsExprs.push_back(StringLiteral::Create(*Context,
2541 clsName->getName(),
2542 StringLiteral::Ascii, false,
2543 argType, SourceLocation()));
2544 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2545 &ClsExprs[0],
2546 ClsExprs.size(),
2547 StartLoc, EndLoc);
2548 MsgExprs.push_back(Cls);
2549
2550 // Create a call to sel_registerName("numberWithBool:"), etc.
2551 // it will be the 2nd argument.
2552 SmallVector<Expr*, 4> SelExprs;
2553 ObjCMethodDecl *NumericMethod = Exp->getObjCNumericLiteralMethod();
2554 SelExprs.push_back(StringLiteral::Create(*Context,
2555 NumericMethod->getSelector().getAsString(),
2556 StringLiteral::Ascii, false,
2557 argType, SourceLocation()));
2558 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2559 &SelExprs[0], SelExprs.size(),
2560 StartLoc, EndLoc);
2561 MsgExprs.push_back(SelExp);
2562
2563 // User provided numeric literal is the 3rd, and last, argument.
2564 Expr *userExpr = Exp->getNumber();
2565 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2566 QualType type = ICE->getType();
2567 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2568 CastKind CK = CK_BitCast;
2569 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2570 CK = CK_IntegralToBoolean;
2571 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2572 }
2573 MsgExprs.push_back(userExpr);
2574
2575 SmallVector<QualType, 4> ArgTypes;
2576 ArgTypes.push_back(Context->getObjCIdType());
2577 ArgTypes.push_back(Context->getObjCSelType());
2578 for (ObjCMethodDecl::param_iterator PI = NumericMethod->param_begin(),
2579 E = NumericMethod->param_end(); PI != E; ++PI)
2580 ArgTypes.push_back((*PI)->getType());
2581
2582 QualType returnType = Exp->getType();
2583 // Get the type, we will need to reference it in a couple spots.
2584 QualType msgSendType = MsgSendFlavor->getType();
2585
2586 // Create a reference to the objc_msgSend() declaration.
2587 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2588 VK_LValue, SourceLocation());
2589
2590 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2591 Context->getPointerType(Context->VoidTy),
2592 CK_BitCast, DRE);
2593
2594 // Now do the "normal" pointer to function cast.
2595 QualType castType =
2596 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2597 NumericMethod->isVariadic());
2598 castType = Context->getPointerType(castType);
2599 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2600 cast);
2601
2602 // Don't forget the parens to enforce the proper binding.
2603 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2604
2605 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2606 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2607 MsgExprs.size(),
2608 FT->getResultType(), VK_RValue,
2609 EndLoc);
2610 ReplaceStmt(Exp, CE);
2611 return CE;
2612}
2613
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002614Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2615 // synthesize declaration of helper functions needed in this routine.
2616 if (!SelGetUidFunctionDecl)
2617 SynthSelGetUidFunctionDecl();
2618 // use objc_msgSend() for all.
2619 if (!MsgSendFunctionDecl)
2620 SynthMsgSendFunctionDecl();
2621 if (!GetClassFunctionDecl)
2622 SynthGetClassFunctionDecl();
2623
2624 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2625 SourceLocation StartLoc = Exp->getLocStart();
2626 SourceLocation EndLoc = Exp->getLocEnd();
2627
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002628 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002629 QualType IntQT = Context->IntTy;
2630 QualType NSArrayFType =
2631 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002632 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002633 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2634 DeclRefExpr *NSArrayDRE =
2635 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2636 SourceLocation());
2637
2638 SmallVector<Expr*, 16> InitExprs;
2639 unsigned NumElements = Exp->getNumElements();
2640 unsigned UnsignedIntSize =
2641 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2642 Expr *count = IntegerLiteral::Create(*Context,
2643 llvm::APInt(UnsignedIntSize, NumElements),
2644 Context->UnsignedIntTy, SourceLocation());
2645 InitExprs.push_back(count);
2646 for (unsigned i = 0; i < NumElements; i++)
2647 InitExprs.push_back(Exp->getElement(i));
2648 Expr *NSArrayCallExpr =
2649 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2650 NSArrayFType, VK_LValue, SourceLocation());
2651
2652 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2653 SourceLocation(),
2654 &Context->Idents.get("arr"),
2655 Context->getPointerType(Context->VoidPtrTy), 0,
2656 /*BitWidth=*/0, /*Mutable=*/true,
2657 /*HasInit=*/false);
2658 MemberExpr *ArrayLiteralME =
2659 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2660 SourceLocation(),
2661 ARRFD->getType(), VK_LValue,
2662 OK_Ordinary);
2663 QualType ConstIdT = Context->getObjCIdType().withConst();
2664 CStyleCastExpr * ArrayLiteralObjects =
2665 NoTypeInfoCStyleCastExpr(Context,
2666 Context->getPointerType(ConstIdT),
2667 CK_BitCast,
2668 ArrayLiteralME);
2669
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002670 // Synthesize a call to objc_msgSend().
2671 SmallVector<Expr*, 32> MsgExprs;
2672 SmallVector<Expr*, 4> ClsExprs;
2673 QualType argType = Context->getPointerType(Context->CharTy);
2674 QualType expType = Exp->getType();
2675
2676 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2677 ObjCInterfaceDecl *Class =
2678 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2679
2680 IdentifierInfo *clsName = Class->getIdentifier();
2681 ClsExprs.push_back(StringLiteral::Create(*Context,
2682 clsName->getName(),
2683 StringLiteral::Ascii, false,
2684 argType, SourceLocation()));
2685 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2686 &ClsExprs[0],
2687 ClsExprs.size(),
2688 StartLoc, EndLoc);
2689 MsgExprs.push_back(Cls);
2690
2691 // Create a call to sel_registerName("arrayWithObjects:count:").
2692 // it will be the 2nd argument.
2693 SmallVector<Expr*, 4> SelExprs;
2694 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2695 SelExprs.push_back(StringLiteral::Create(*Context,
2696 ArrayMethod->getSelector().getAsString(),
2697 StringLiteral::Ascii, false,
2698 argType, SourceLocation()));
2699 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2700 &SelExprs[0], SelExprs.size(),
2701 StartLoc, EndLoc);
2702 MsgExprs.push_back(SelExp);
2703
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002704 // (const id [])objects
2705 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002706
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002707 // (NSUInteger)cnt
2708 Expr *cnt = IntegerLiteral::Create(*Context,
2709 llvm::APInt(UnsignedIntSize, NumElements),
2710 Context->UnsignedIntTy, SourceLocation());
2711 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002712
2713
2714 SmallVector<QualType, 4> ArgTypes;
2715 ArgTypes.push_back(Context->getObjCIdType());
2716 ArgTypes.push_back(Context->getObjCSelType());
2717 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2718 E = ArrayMethod->param_end(); PI != E; ++PI)
2719 ArgTypes.push_back((*PI)->getType());
2720
2721 QualType returnType = Exp->getType();
2722 // Get the type, we will need to reference it in a couple spots.
2723 QualType msgSendType = MsgSendFlavor->getType();
2724
2725 // Create a reference to the objc_msgSend() declaration.
2726 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2727 VK_LValue, SourceLocation());
2728
2729 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2730 Context->getPointerType(Context->VoidTy),
2731 CK_BitCast, DRE);
2732
2733 // Now do the "normal" pointer to function cast.
2734 QualType castType =
2735 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2736 ArrayMethod->isVariadic());
2737 castType = Context->getPointerType(castType);
2738 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2739 cast);
2740
2741 // Don't forget the parens to enforce the proper binding.
2742 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2743
2744 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2745 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2746 MsgExprs.size(),
2747 FT->getResultType(), VK_RValue,
2748 EndLoc);
2749 ReplaceStmt(Exp, CE);
2750 return CE;
2751}
2752
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002753Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2754 // synthesize declaration of helper functions needed in this routine.
2755 if (!SelGetUidFunctionDecl)
2756 SynthSelGetUidFunctionDecl();
2757 // use objc_msgSend() for all.
2758 if (!MsgSendFunctionDecl)
2759 SynthMsgSendFunctionDecl();
2760 if (!GetClassFunctionDecl)
2761 SynthGetClassFunctionDecl();
2762
2763 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2764 SourceLocation StartLoc = Exp->getLocStart();
2765 SourceLocation EndLoc = Exp->getLocEnd();
2766
2767 // Build the expression: __NSContainer_literal(int, ...).arr
2768 QualType IntQT = Context->IntTy;
2769 QualType NSDictFType =
2770 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2771 std::string NSDictFName("__NSContainer_literal");
2772 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2773 DeclRefExpr *NSDictDRE =
2774 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2775 SourceLocation());
2776
2777 SmallVector<Expr*, 16> KeyExprs;
2778 SmallVector<Expr*, 16> ValueExprs;
2779
2780 unsigned NumElements = Exp->getNumElements();
2781 unsigned UnsignedIntSize =
2782 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2783 Expr *count = IntegerLiteral::Create(*Context,
2784 llvm::APInt(UnsignedIntSize, NumElements),
2785 Context->UnsignedIntTy, SourceLocation());
2786 KeyExprs.push_back(count);
2787 ValueExprs.push_back(count);
2788 for (unsigned i = 0; i < NumElements; i++) {
2789 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2790 KeyExprs.push_back(Element.Key);
2791 ValueExprs.push_back(Element.Value);
2792 }
2793
2794 // (const id [])objects
2795 Expr *NSValueCallExpr =
2796 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2797 NSDictFType, VK_LValue, SourceLocation());
2798
2799 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2800 SourceLocation(),
2801 &Context->Idents.get("arr"),
2802 Context->getPointerType(Context->VoidPtrTy), 0,
2803 /*BitWidth=*/0, /*Mutable=*/true,
2804 /*HasInit=*/false);
2805 MemberExpr *DictLiteralValueME =
2806 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2807 SourceLocation(),
2808 ARRFD->getType(), VK_LValue,
2809 OK_Ordinary);
2810 QualType ConstIdT = Context->getObjCIdType().withConst();
2811 CStyleCastExpr * DictValueObjects =
2812 NoTypeInfoCStyleCastExpr(Context,
2813 Context->getPointerType(ConstIdT),
2814 CK_BitCast,
2815 DictLiteralValueME);
2816 // (const id <NSCopying> [])keys
2817 Expr *NSKeyCallExpr =
2818 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2819 NSDictFType, VK_LValue, SourceLocation());
2820
2821 MemberExpr *DictLiteralKeyME =
2822 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2823 SourceLocation(),
2824 ARRFD->getType(), VK_LValue,
2825 OK_Ordinary);
2826
2827 CStyleCastExpr * DictKeyObjects =
2828 NoTypeInfoCStyleCastExpr(Context,
2829 Context->getPointerType(ConstIdT),
2830 CK_BitCast,
2831 DictLiteralKeyME);
2832
2833
2834
2835 // Synthesize a call to objc_msgSend().
2836 SmallVector<Expr*, 32> MsgExprs;
2837 SmallVector<Expr*, 4> ClsExprs;
2838 QualType argType = Context->getPointerType(Context->CharTy);
2839 QualType expType = Exp->getType();
2840
2841 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2842 ObjCInterfaceDecl *Class =
2843 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2844
2845 IdentifierInfo *clsName = Class->getIdentifier();
2846 ClsExprs.push_back(StringLiteral::Create(*Context,
2847 clsName->getName(),
2848 StringLiteral::Ascii, false,
2849 argType, SourceLocation()));
2850 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2851 &ClsExprs[0],
2852 ClsExprs.size(),
2853 StartLoc, EndLoc);
2854 MsgExprs.push_back(Cls);
2855
2856 // Create a call to sel_registerName("arrayWithObjects:count:").
2857 // it will be the 2nd argument.
2858 SmallVector<Expr*, 4> SelExprs;
2859 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2860 SelExprs.push_back(StringLiteral::Create(*Context,
2861 DictMethod->getSelector().getAsString(),
2862 StringLiteral::Ascii, false,
2863 argType, SourceLocation()));
2864 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2865 &SelExprs[0], SelExprs.size(),
2866 StartLoc, EndLoc);
2867 MsgExprs.push_back(SelExp);
2868
2869 // (const id [])objects
2870 MsgExprs.push_back(DictValueObjects);
2871
2872 // (const id <NSCopying> [])keys
2873 MsgExprs.push_back(DictKeyObjects);
2874
2875 // (NSUInteger)cnt
2876 Expr *cnt = IntegerLiteral::Create(*Context,
2877 llvm::APInt(UnsignedIntSize, NumElements),
2878 Context->UnsignedIntTy, SourceLocation());
2879 MsgExprs.push_back(cnt);
2880
2881
2882 SmallVector<QualType, 8> ArgTypes;
2883 ArgTypes.push_back(Context->getObjCIdType());
2884 ArgTypes.push_back(Context->getObjCSelType());
2885 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2886 E = DictMethod->param_end(); PI != E; ++PI) {
2887 QualType T = (*PI)->getType();
2888 if (const PointerType* PT = T->getAs<PointerType>()) {
2889 QualType PointeeTy = PT->getPointeeType();
2890 convertToUnqualifiedObjCType(PointeeTy);
2891 T = Context->getPointerType(PointeeTy);
2892 }
2893 ArgTypes.push_back(T);
2894 }
2895
2896 QualType returnType = Exp->getType();
2897 // Get the type, we will need to reference it in a couple spots.
2898 QualType msgSendType = MsgSendFlavor->getType();
2899
2900 // Create a reference to the objc_msgSend() declaration.
2901 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2902 VK_LValue, SourceLocation());
2903
2904 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2905 Context->getPointerType(Context->VoidTy),
2906 CK_BitCast, DRE);
2907
2908 // Now do the "normal" pointer to function cast.
2909 QualType castType =
2910 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2911 DictMethod->isVariadic());
2912 castType = Context->getPointerType(castType);
2913 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2914 cast);
2915
2916 // Don't forget the parens to enforce the proper binding.
2917 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2918
2919 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2920 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2921 MsgExprs.size(),
2922 FT->getResultType(), VK_RValue,
2923 EndLoc);
2924 ReplaceStmt(Exp, CE);
2925 return CE;
2926}
2927
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002928// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2929QualType RewriteModernObjC::getSuperStructType() {
2930 if (!SuperStructDecl) {
2931 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2932 SourceLocation(), SourceLocation(),
2933 &Context->Idents.get("objc_super"));
2934 QualType FieldTypes[2];
2935
2936 // struct objc_object *receiver;
2937 FieldTypes[0] = Context->getObjCIdType();
2938 // struct objc_class *super;
2939 FieldTypes[1] = Context->getObjCClassType();
2940
2941 // Create fields
2942 for (unsigned i = 0; i < 2; ++i) {
2943 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2944 SourceLocation(),
2945 SourceLocation(), 0,
2946 FieldTypes[i], 0,
2947 /*BitWidth=*/0,
2948 /*Mutable=*/false,
2949 /*HasInit=*/false));
2950 }
2951
2952 SuperStructDecl->completeDefinition();
2953 }
2954 return Context->getTagDeclType(SuperStructDecl);
2955}
2956
2957QualType RewriteModernObjC::getConstantStringStructType() {
2958 if (!ConstantStringDecl) {
2959 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2960 SourceLocation(), SourceLocation(),
2961 &Context->Idents.get("__NSConstantStringImpl"));
2962 QualType FieldTypes[4];
2963
2964 // struct objc_object *receiver;
2965 FieldTypes[0] = Context->getObjCIdType();
2966 // int flags;
2967 FieldTypes[1] = Context->IntTy;
2968 // char *str;
2969 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2970 // long length;
2971 FieldTypes[3] = Context->LongTy;
2972
2973 // Create fields
2974 for (unsigned i = 0; i < 4; ++i) {
2975 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2976 ConstantStringDecl,
2977 SourceLocation(),
2978 SourceLocation(), 0,
2979 FieldTypes[i], 0,
2980 /*BitWidth=*/0,
2981 /*Mutable=*/true,
2982 /*HasInit=*/false));
2983 }
2984
2985 ConstantStringDecl->completeDefinition();
2986 }
2987 return Context->getTagDeclType(ConstantStringDecl);
2988}
2989
2990Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2991 SourceLocation StartLoc,
2992 SourceLocation EndLoc) {
2993 if (!SelGetUidFunctionDecl)
2994 SynthSelGetUidFunctionDecl();
2995 if (!MsgSendFunctionDecl)
2996 SynthMsgSendFunctionDecl();
2997 if (!MsgSendSuperFunctionDecl)
2998 SynthMsgSendSuperFunctionDecl();
2999 if (!MsgSendStretFunctionDecl)
3000 SynthMsgSendStretFunctionDecl();
3001 if (!MsgSendSuperStretFunctionDecl)
3002 SynthMsgSendSuperStretFunctionDecl();
3003 if (!MsgSendFpretFunctionDecl)
3004 SynthMsgSendFpretFunctionDecl();
3005 if (!GetClassFunctionDecl)
3006 SynthGetClassFunctionDecl();
3007 if (!GetSuperClassFunctionDecl)
3008 SynthGetSuperClassFunctionDecl();
3009 if (!GetMetaClassFunctionDecl)
3010 SynthGetMetaClassFunctionDecl();
3011
3012 // default to objc_msgSend().
3013 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3014 // May need to use objc_msgSend_stret() as well.
3015 FunctionDecl *MsgSendStretFlavor = 0;
3016 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3017 QualType resultType = mDecl->getResultType();
3018 if (resultType->isRecordType())
3019 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3020 else if (resultType->isRealFloatingType())
3021 MsgSendFlavor = MsgSendFpretFunctionDecl;
3022 }
3023
3024 // Synthesize a call to objc_msgSend().
3025 SmallVector<Expr*, 8> MsgExprs;
3026 switch (Exp->getReceiverKind()) {
3027 case ObjCMessageExpr::SuperClass: {
3028 MsgSendFlavor = MsgSendSuperFunctionDecl;
3029 if (MsgSendStretFlavor)
3030 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3031 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3032
3033 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3034
3035 SmallVector<Expr*, 4> InitExprs;
3036
3037 // set the receiver to self, the first argument to all methods.
3038 InitExprs.push_back(
3039 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3040 CK_BitCast,
3041 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003042 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003043 Context->getObjCIdType(),
3044 VK_RValue,
3045 SourceLocation()))
3046 ); // set the 'receiver'.
3047
3048 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3049 SmallVector<Expr*, 8> ClsExprs;
3050 QualType argType = Context->getPointerType(Context->CharTy);
3051 ClsExprs.push_back(StringLiteral::Create(*Context,
3052 ClassDecl->getIdentifier()->getName(),
3053 StringLiteral::Ascii, false,
3054 argType, SourceLocation()));
3055 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3056 &ClsExprs[0],
3057 ClsExprs.size(),
3058 StartLoc,
3059 EndLoc);
3060 // (Class)objc_getClass("CurrentClass")
3061 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3062 Context->getObjCClassType(),
3063 CK_BitCast, Cls);
3064 ClsExprs.clear();
3065 ClsExprs.push_back(ArgExpr);
3066 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3067 &ClsExprs[0], ClsExprs.size(),
3068 StartLoc, EndLoc);
3069
3070 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3071 // To turn off a warning, type-cast to 'id'
3072 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3073 NoTypeInfoCStyleCastExpr(Context,
3074 Context->getObjCIdType(),
3075 CK_BitCast, Cls));
3076 // struct objc_super
3077 QualType superType = getSuperStructType();
3078 Expr *SuperRep;
3079
3080 if (LangOpts.MicrosoftExt) {
3081 SynthSuperContructorFunctionDecl();
3082 // Simulate a contructor call...
3083 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003084 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003085 SourceLocation());
3086 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3087 InitExprs.size(),
3088 superType, VK_LValue,
3089 SourceLocation());
3090 // The code for super is a little tricky to prevent collision with
3091 // the structure definition in the header. The rewriter has it's own
3092 // internal definition (__rw_objc_super) that is uses. This is why
3093 // we need the cast below. For example:
3094 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3095 //
3096 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3097 Context->getPointerType(SuperRep->getType()),
3098 VK_RValue, OK_Ordinary,
3099 SourceLocation());
3100 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3101 Context->getPointerType(superType),
3102 CK_BitCast, SuperRep);
3103 } else {
3104 // (struct objc_super) { <exprs from above> }
3105 InitListExpr *ILE =
3106 new (Context) InitListExpr(*Context, SourceLocation(),
3107 &InitExprs[0], InitExprs.size(),
3108 SourceLocation());
3109 TypeSourceInfo *superTInfo
3110 = Context->getTrivialTypeSourceInfo(superType);
3111 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3112 superType, VK_LValue,
3113 ILE, false);
3114 // struct objc_super *
3115 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3116 Context->getPointerType(SuperRep->getType()),
3117 VK_RValue, OK_Ordinary,
3118 SourceLocation());
3119 }
3120 MsgExprs.push_back(SuperRep);
3121 break;
3122 }
3123
3124 case ObjCMessageExpr::Class: {
3125 SmallVector<Expr*, 8> ClsExprs;
3126 QualType argType = Context->getPointerType(Context->CharTy);
3127 ObjCInterfaceDecl *Class
3128 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3129 IdentifierInfo *clsName = Class->getIdentifier();
3130 ClsExprs.push_back(StringLiteral::Create(*Context,
3131 clsName->getName(),
3132 StringLiteral::Ascii, false,
3133 argType, SourceLocation()));
3134 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3135 &ClsExprs[0],
3136 ClsExprs.size(),
3137 StartLoc, EndLoc);
3138 MsgExprs.push_back(Cls);
3139 break;
3140 }
3141
3142 case ObjCMessageExpr::SuperInstance:{
3143 MsgSendFlavor = MsgSendSuperFunctionDecl;
3144 if (MsgSendStretFlavor)
3145 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3146 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3147 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3148 SmallVector<Expr*, 4> InitExprs;
3149
3150 InitExprs.push_back(
3151 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3152 CK_BitCast,
3153 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003154 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003155 Context->getObjCIdType(),
3156 VK_RValue, SourceLocation()))
3157 ); // set the 'receiver'.
3158
3159 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3160 SmallVector<Expr*, 8> ClsExprs;
3161 QualType argType = Context->getPointerType(Context->CharTy);
3162 ClsExprs.push_back(StringLiteral::Create(*Context,
3163 ClassDecl->getIdentifier()->getName(),
3164 StringLiteral::Ascii, false, argType,
3165 SourceLocation()));
3166 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3167 &ClsExprs[0],
3168 ClsExprs.size(),
3169 StartLoc, EndLoc);
3170 // (Class)objc_getClass("CurrentClass")
3171 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3172 Context->getObjCClassType(),
3173 CK_BitCast, Cls);
3174 ClsExprs.clear();
3175 ClsExprs.push_back(ArgExpr);
3176 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3177 &ClsExprs[0], ClsExprs.size(),
3178 StartLoc, EndLoc);
3179
3180 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3181 // To turn off a warning, type-cast to 'id'
3182 InitExprs.push_back(
3183 // set 'super class', using class_getSuperclass().
3184 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3185 CK_BitCast, Cls));
3186 // struct objc_super
3187 QualType superType = getSuperStructType();
3188 Expr *SuperRep;
3189
3190 if (LangOpts.MicrosoftExt) {
3191 SynthSuperContructorFunctionDecl();
3192 // Simulate a contructor call...
3193 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003194 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003195 SourceLocation());
3196 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3197 InitExprs.size(),
3198 superType, VK_LValue, SourceLocation());
3199 // The code for super is a little tricky to prevent collision with
3200 // the structure definition in the header. The rewriter has it's own
3201 // internal definition (__rw_objc_super) that is uses. This is why
3202 // we need the cast below. For example:
3203 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3204 //
3205 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3206 Context->getPointerType(SuperRep->getType()),
3207 VK_RValue, OK_Ordinary,
3208 SourceLocation());
3209 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3210 Context->getPointerType(superType),
3211 CK_BitCast, SuperRep);
3212 } else {
3213 // (struct objc_super) { <exprs from above> }
3214 InitListExpr *ILE =
3215 new (Context) InitListExpr(*Context, SourceLocation(),
3216 &InitExprs[0], InitExprs.size(),
3217 SourceLocation());
3218 TypeSourceInfo *superTInfo
3219 = Context->getTrivialTypeSourceInfo(superType);
3220 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3221 superType, VK_RValue, ILE,
3222 false);
3223 }
3224 MsgExprs.push_back(SuperRep);
3225 break;
3226 }
3227
3228 case ObjCMessageExpr::Instance: {
3229 // Remove all type-casts because it may contain objc-style types; e.g.
3230 // Foo<Proto> *.
3231 Expr *recExpr = Exp->getInstanceReceiver();
3232 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3233 recExpr = CE->getSubExpr();
3234 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3235 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3236 ? CK_BlockPointerToObjCPointerCast
3237 : CK_CPointerToObjCPointerCast;
3238
3239 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3240 CK, recExpr);
3241 MsgExprs.push_back(recExpr);
3242 break;
3243 }
3244 }
3245
3246 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3247 SmallVector<Expr*, 8> SelExprs;
3248 QualType argType = Context->getPointerType(Context->CharTy);
3249 SelExprs.push_back(StringLiteral::Create(*Context,
3250 Exp->getSelector().getAsString(),
3251 StringLiteral::Ascii, false,
3252 argType, SourceLocation()));
3253 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3254 &SelExprs[0], SelExprs.size(),
3255 StartLoc,
3256 EndLoc);
3257 MsgExprs.push_back(SelExp);
3258
3259 // Now push any user supplied arguments.
3260 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3261 Expr *userExpr = Exp->getArg(i);
3262 // Make all implicit casts explicit...ICE comes in handy:-)
3263 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3264 // Reuse the ICE type, it is exactly what the doctor ordered.
3265 QualType type = ICE->getType();
3266 if (needToScanForQualifiers(type))
3267 type = Context->getObjCIdType();
3268 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3269 (void)convertBlockPointerToFunctionPointer(type);
3270 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3271 CastKind CK;
3272 if (SubExpr->getType()->isIntegralType(*Context) &&
3273 type->isBooleanType()) {
3274 CK = CK_IntegralToBoolean;
3275 } else if (type->isObjCObjectPointerType()) {
3276 if (SubExpr->getType()->isBlockPointerType()) {
3277 CK = CK_BlockPointerToObjCPointerCast;
3278 } else if (SubExpr->getType()->isPointerType()) {
3279 CK = CK_CPointerToObjCPointerCast;
3280 } else {
3281 CK = CK_BitCast;
3282 }
3283 } else {
3284 CK = CK_BitCast;
3285 }
3286
3287 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3288 }
3289 // Make id<P...> cast into an 'id' cast.
3290 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3291 if (CE->getType()->isObjCQualifiedIdType()) {
3292 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3293 userExpr = CE->getSubExpr();
3294 CastKind CK;
3295 if (userExpr->getType()->isIntegralType(*Context)) {
3296 CK = CK_IntegralToPointer;
3297 } else if (userExpr->getType()->isBlockPointerType()) {
3298 CK = CK_BlockPointerToObjCPointerCast;
3299 } else if (userExpr->getType()->isPointerType()) {
3300 CK = CK_CPointerToObjCPointerCast;
3301 } else {
3302 CK = CK_BitCast;
3303 }
3304 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3305 CK, userExpr);
3306 }
3307 }
3308 MsgExprs.push_back(userExpr);
3309 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3310 // out the argument in the original expression (since we aren't deleting
3311 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3312 //Exp->setArg(i, 0);
3313 }
3314 // Generate the funky cast.
3315 CastExpr *cast;
3316 SmallVector<QualType, 8> ArgTypes;
3317 QualType returnType;
3318
3319 // Push 'id' and 'SEL', the 2 implicit arguments.
3320 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3321 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3322 else
3323 ArgTypes.push_back(Context->getObjCIdType());
3324 ArgTypes.push_back(Context->getObjCSelType());
3325 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3326 // Push any user argument types.
3327 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3328 E = OMD->param_end(); PI != E; ++PI) {
3329 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3330 ? Context->getObjCIdType()
3331 : (*PI)->getType();
3332 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3333 (void)convertBlockPointerToFunctionPointer(t);
3334 ArgTypes.push_back(t);
3335 }
3336 returnType = Exp->getType();
3337 convertToUnqualifiedObjCType(returnType);
3338 (void)convertBlockPointerToFunctionPointer(returnType);
3339 } else {
3340 returnType = Context->getObjCIdType();
3341 }
3342 // Get the type, we will need to reference it in a couple spots.
3343 QualType msgSendType = MsgSendFlavor->getType();
3344
3345 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003346 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003347 VK_LValue, SourceLocation());
3348
3349 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3350 // If we don't do this cast, we get the following bizarre warning/note:
3351 // xx.m:13: warning: function called through a non-compatible type
3352 // xx.m:13: note: if this code is reached, the program will abort
3353 cast = NoTypeInfoCStyleCastExpr(Context,
3354 Context->getPointerType(Context->VoidTy),
3355 CK_BitCast, DRE);
3356
3357 // Now do the "normal" pointer to function cast.
3358 QualType castType =
3359 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3360 // If we don't have a method decl, force a variadic cast.
3361 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3362 castType = Context->getPointerType(castType);
3363 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3364 cast);
3365
3366 // Don't forget the parens to enforce the proper binding.
3367 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3368
3369 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3370 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3371 MsgExprs.size(),
3372 FT->getResultType(), VK_RValue,
3373 EndLoc);
3374 Stmt *ReplacingStmt = CE;
3375 if (MsgSendStretFlavor) {
3376 // We have the method which returns a struct/union. Must also generate
3377 // call to objc_msgSend_stret and hang both varieties on a conditional
3378 // expression which dictate which one to envoke depending on size of
3379 // method's return type.
3380
3381 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003382 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3383 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003384 VK_LValue, SourceLocation());
3385 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3386 cast = NoTypeInfoCStyleCastExpr(Context,
3387 Context->getPointerType(Context->VoidTy),
3388 CK_BitCast, STDRE);
3389 // Now do the "normal" pointer to function cast.
3390 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3391 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3392 castType = Context->getPointerType(castType);
3393 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3394 cast);
3395
3396 // Don't forget the parens to enforce the proper binding.
3397 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3398
3399 FT = msgSendType->getAs<FunctionType>();
3400 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3401 MsgExprs.size(),
3402 FT->getResultType(), VK_RValue,
3403 SourceLocation());
3404
3405 // Build sizeof(returnType)
3406 UnaryExprOrTypeTraitExpr *sizeofExpr =
3407 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3408 Context->getTrivialTypeSourceInfo(returnType),
3409 Context->getSizeType(), SourceLocation(),
3410 SourceLocation());
3411 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3412 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3413 // For X86 it is more complicated and some kind of target specific routine
3414 // is needed to decide what to do.
3415 unsigned IntSize =
3416 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3417 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3418 llvm::APInt(IntSize, 8),
3419 Context->IntTy,
3420 SourceLocation());
3421 BinaryOperator *lessThanExpr =
3422 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3423 VK_RValue, OK_Ordinary, SourceLocation());
3424 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3425 ConditionalOperator *CondExpr =
3426 new (Context) ConditionalOperator(lessThanExpr,
3427 SourceLocation(), CE,
3428 SourceLocation(), STCE,
3429 returnType, VK_RValue, OK_Ordinary);
3430 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3431 CondExpr);
3432 }
3433 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3434 return ReplacingStmt;
3435}
3436
3437Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3438 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3439 Exp->getLocEnd());
3440
3441 // Now do the actual rewrite.
3442 ReplaceStmt(Exp, ReplacingStmt);
3443
3444 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3445 return ReplacingStmt;
3446}
3447
3448// typedef struct objc_object Protocol;
3449QualType RewriteModernObjC::getProtocolType() {
3450 if (!ProtocolTypeDecl) {
3451 TypeSourceInfo *TInfo
3452 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3453 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3454 SourceLocation(), SourceLocation(),
3455 &Context->Idents.get("Protocol"),
3456 TInfo);
3457 }
3458 return Context->getTypeDeclType(ProtocolTypeDecl);
3459}
3460
3461/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3462/// a synthesized/forward data reference (to the protocol's metadata).
3463/// The forward references (and metadata) are generated in
3464/// RewriteModernObjC::HandleTranslationUnit().
3465Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003466 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3467 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003468 IdentifierInfo *ID = &Context->Idents.get(Name);
3469 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3470 SourceLocation(), ID, getProtocolType(), 0,
3471 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003472 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3473 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003474 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3475 Context->getPointerType(DRE->getType()),
3476 VK_RValue, OK_Ordinary, SourceLocation());
3477 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3478 CK_BitCast,
3479 DerefExpr);
3480 ReplaceStmt(Exp, castExpr);
3481 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3482 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3483 return castExpr;
3484
3485}
3486
3487bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3488 const char *endBuf) {
3489 while (startBuf < endBuf) {
3490 if (*startBuf == '#') {
3491 // Skip whitespace.
3492 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3493 ;
3494 if (!strncmp(startBuf, "if", strlen("if")) ||
3495 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3496 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3497 !strncmp(startBuf, "define", strlen("define")) ||
3498 !strncmp(startBuf, "undef", strlen("undef")) ||
3499 !strncmp(startBuf, "else", strlen("else")) ||
3500 !strncmp(startBuf, "elif", strlen("elif")) ||
3501 !strncmp(startBuf, "endif", strlen("endif")) ||
3502 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3503 !strncmp(startBuf, "include", strlen("include")) ||
3504 !strncmp(startBuf, "import", strlen("import")) ||
3505 !strncmp(startBuf, "include_next", strlen("include_next")))
3506 return true;
3507 }
3508 startBuf++;
3509 }
3510 return false;
3511}
3512
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003513/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003514/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003515bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3516 std::string &Result) {
3517 if (Type->isArrayType()) {
3518 QualType ElemTy = Context->getBaseElementType(Type);
3519 return RewriteObjCFieldDeclType(ElemTy, Result);
3520 }
3521 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003522 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3523 if (RD->isCompleteDefinition()) {
3524 if (RD->isStruct())
3525 Result += "\n\tstruct ";
3526 else if (RD->isUnion())
3527 Result += "\n\tunion ";
3528 else
3529 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003530
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003531 Result += RD->getName();
3532 if (TagsDefinedInIvarDecls.count(RD)) {
3533 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003534 Result += " ";
3535 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003536 }
3537 TagsDefinedInIvarDecls.insert(RD);
3538 Result += " {\n";
3539 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003540 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003541 FieldDecl *FD = *i;
3542 RewriteObjCFieldDecl(FD, Result);
3543 }
3544 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003545 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003546 }
3547 }
3548 else if (Type->isEnumeralType()) {
3549 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3550 if (ED->isCompleteDefinition()) {
3551 Result += "\n\tenum ";
3552 Result += ED->getName();
3553 if (TagsDefinedInIvarDecls.count(ED)) {
3554 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003555 Result += " ";
3556 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003557 }
3558 TagsDefinedInIvarDecls.insert(ED);
3559
3560 Result += " {\n";
3561 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3562 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3563 Result += "\t"; Result += EC->getName(); Result += " = ";
3564 llvm::APSInt Val = EC->getInitVal();
3565 Result += Val.toString(10);
3566 Result += ",\n";
3567 }
3568 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003569 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003570 }
3571 }
3572
3573 Result += "\t";
3574 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003575 return false;
3576}
3577
3578
3579/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3580/// It handles elaborated types, as well as enum types in the process.
3581void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3582 std::string &Result) {
3583 QualType Type = fieldDecl->getType();
3584 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003585
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003586 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3587 if (!EleboratedType)
3588 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003589 Result += Name;
3590 if (fieldDecl->isBitField()) {
3591 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3592 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003593 else if (EleboratedType && Type->isArrayType()) {
3594 CanQualType CType = Context->getCanonicalType(Type);
3595 while (isa<ArrayType>(CType)) {
3596 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3597 Result += "[";
3598 llvm::APInt Dim = CAT->getSize();
3599 Result += utostr(Dim.getZExtValue());
3600 Result += "]";
3601 }
3602 CType = CType->getAs<ArrayType>()->getElementType();
3603 }
3604 }
3605
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003606 Result += ";\n";
3607}
3608
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003609/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3610/// an objective-c class with ivars.
3611void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3612 std::string &Result) {
3613 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3614 assert(CDecl->getName() != "" &&
3615 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003616 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003617 SmallVector<ObjCIvarDecl *, 8> IVars;
3618 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003619 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003620 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003621
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003622 SourceLocation LocStart = CDecl->getLocStart();
3623 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003624
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003625 const char *startBuf = SM->getCharacterData(LocStart);
3626 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003627
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003628 // If no ivars and no root or if its root, directly or indirectly,
3629 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003630 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003631 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3632 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3633 ReplaceText(LocStart, endBuf-startBuf, Result);
3634 return;
3635 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003636
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003637 Result += "\nstruct ";
3638 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003639 Result += "_IMPL {\n";
3640
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003641 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003642 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3643 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3644 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003645 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003646 TagsDefinedInIvarDecls.clear();
3647 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3648 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003649
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003650 Result += "};\n";
3651 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3652 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003653 // Mark this struct as having been generated.
3654 if (!ObjCSynthesizedStructs.insert(CDecl))
3655 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003656}
3657
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003658static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3659 ObjCIvarDecl *IvarDecl, std::string &Result) {
3660 Result += "OBJC_IVAR_$_";
3661 Result += IDecl->getName();
3662 Result += "$";
3663 Result += IvarDecl->getName();
3664}
3665
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003666/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3667/// have been referenced in an ivar access expression.
3668void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3669 std::string &Result) {
3670 // write out ivar offset symbols which have been referenced in an ivar
3671 // access expression.
3672 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3673 if (Ivars.empty())
3674 return;
3675 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3676 e = Ivars.end(); i != e; i++) {
3677 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003678 Result += "\n";
3679 if (LangOpts.MicrosoftExt)
3680 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003681 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003682 if (LangOpts.MicrosoftExt &&
3683 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003684 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3685 Result += "__declspec(dllimport) ";
3686
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003687 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003688 WriteInternalIvarName(CDecl, IvarDecl, Result);
3689 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003690 }
3691}
3692
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003693//===----------------------------------------------------------------------===//
3694// Meta Data Emission
3695//===----------------------------------------------------------------------===//
3696
3697
3698/// RewriteImplementations - This routine rewrites all method implementations
3699/// and emits meta-data.
3700
3701void RewriteModernObjC::RewriteImplementations() {
3702 int ClsDefCount = ClassImplementation.size();
3703 int CatDefCount = CategoryImplementation.size();
3704
3705 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003706 for (int i = 0; i < ClsDefCount; i++) {
3707 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3708 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3709 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003710 assert(false &&
3711 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003712 RewriteImplementationDecl(OIMP);
3713 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003714
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003715 for (int i = 0; i < CatDefCount; i++) {
3716 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3717 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3718 if (CDecl->isImplicitInterfaceDecl())
3719 assert(false &&
3720 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003721 RewriteImplementationDecl(CIMP);
3722 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003723}
3724
3725void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3726 const std::string &Name,
3727 ValueDecl *VD, bool def) {
3728 assert(BlockByRefDeclNo.count(VD) &&
3729 "RewriteByRefString: ByRef decl missing");
3730 if (def)
3731 ResultStr += "struct ";
3732 ResultStr += "__Block_byref_" + Name +
3733 "_" + utostr(BlockByRefDeclNo[VD]) ;
3734}
3735
3736static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3737 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3738 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3739 return false;
3740}
3741
3742std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3743 StringRef funcName,
3744 std::string Tag) {
3745 const FunctionType *AFT = CE->getFunctionType();
3746 QualType RT = AFT->getResultType();
3747 std::string StructRef = "struct " + Tag;
3748 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003749 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003750
3751 BlockDecl *BD = CE->getBlockDecl();
3752
3753 if (isa<FunctionNoProtoType>(AFT)) {
3754 // No user-supplied arguments. Still need to pass in a pointer to the
3755 // block (to reference imported block decl refs).
3756 S += "(" + StructRef + " *__cself)";
3757 } else if (BD->param_empty()) {
3758 S += "(" + StructRef + " *__cself)";
3759 } else {
3760 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3761 assert(FT && "SynthesizeBlockFunc: No function proto");
3762 S += '(';
3763 // first add the implicit argument.
3764 S += StructRef + " *__cself, ";
3765 std::string ParamStr;
3766 for (BlockDecl::param_iterator AI = BD->param_begin(),
3767 E = BD->param_end(); AI != E; ++AI) {
3768 if (AI != BD->param_begin()) S += ", ";
3769 ParamStr = (*AI)->getNameAsString();
3770 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003771 (void)convertBlockPointerToFunctionPointer(QT);
3772 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003773 S += ParamStr;
3774 }
3775 if (FT->isVariadic()) {
3776 if (!BD->param_empty()) S += ", ";
3777 S += "...";
3778 }
3779 S += ')';
3780 }
3781 S += " {\n";
3782
3783 // Create local declarations to avoid rewriting all closure decl ref exprs.
3784 // First, emit a declaration for all "by ref" decls.
3785 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3786 E = BlockByRefDecls.end(); I != E; ++I) {
3787 S += " ";
3788 std::string Name = (*I)->getNameAsString();
3789 std::string TypeString;
3790 RewriteByRefString(TypeString, Name, (*I));
3791 TypeString += " *";
3792 Name = TypeString + Name;
3793 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3794 }
3795 // Next, emit a declaration for all "by copy" declarations.
3796 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3797 E = BlockByCopyDecls.end(); I != E; ++I) {
3798 S += " ";
3799 // Handle nested closure invocation. For example:
3800 //
3801 // void (^myImportedClosure)(void);
3802 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3803 //
3804 // void (^anotherClosure)(void);
3805 // anotherClosure = ^(void) {
3806 // myImportedClosure(); // import and invoke the closure
3807 // };
3808 //
3809 if (isTopLevelBlockPointerType((*I)->getType())) {
3810 RewriteBlockPointerTypeVariable(S, (*I));
3811 S += " = (";
3812 RewriteBlockPointerType(S, (*I)->getType());
3813 S += ")";
3814 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3815 }
3816 else {
3817 std::string Name = (*I)->getNameAsString();
3818 QualType QT = (*I)->getType();
3819 if (HasLocalVariableExternalStorage(*I))
3820 QT = Context->getPointerType(QT);
3821 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3822 S += Name + " = __cself->" +
3823 (*I)->getNameAsString() + "; // bound by copy\n";
3824 }
3825 }
3826 std::string RewrittenStr = RewrittenBlockExprs[CE];
3827 const char *cstr = RewrittenStr.c_str();
3828 while (*cstr++ != '{') ;
3829 S += cstr;
3830 S += "\n";
3831 return S;
3832}
3833
3834std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3835 StringRef funcName,
3836 std::string Tag) {
3837 std::string StructRef = "struct " + Tag;
3838 std::string S = "static void __";
3839
3840 S += funcName;
3841 S += "_block_copy_" + utostr(i);
3842 S += "(" + StructRef;
3843 S += "*dst, " + StructRef;
3844 S += "*src) {";
3845 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3846 E = ImportedBlockDecls.end(); I != E; ++I) {
3847 ValueDecl *VD = (*I);
3848 S += "_Block_object_assign((void*)&dst->";
3849 S += (*I)->getNameAsString();
3850 S += ", (void*)src->";
3851 S += (*I)->getNameAsString();
3852 if (BlockByRefDeclsPtrSet.count((*I)))
3853 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3854 else if (VD->getType()->isBlockPointerType())
3855 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3856 else
3857 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3858 }
3859 S += "}\n";
3860
3861 S += "\nstatic void __";
3862 S += funcName;
3863 S += "_block_dispose_" + utostr(i);
3864 S += "(" + StructRef;
3865 S += "*src) {";
3866 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3867 E = ImportedBlockDecls.end(); I != E; ++I) {
3868 ValueDecl *VD = (*I);
3869 S += "_Block_object_dispose((void*)src->";
3870 S += (*I)->getNameAsString();
3871 if (BlockByRefDeclsPtrSet.count((*I)))
3872 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3873 else if (VD->getType()->isBlockPointerType())
3874 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3875 else
3876 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3877 }
3878 S += "}\n";
3879 return S;
3880}
3881
3882std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3883 std::string Desc) {
3884 std::string S = "\nstruct " + Tag;
3885 std::string Constructor = " " + Tag;
3886
3887 S += " {\n struct __block_impl impl;\n";
3888 S += " struct " + Desc;
3889 S += "* Desc;\n";
3890
3891 Constructor += "(void *fp, "; // Invoke function pointer.
3892 Constructor += "struct " + Desc; // Descriptor pointer.
3893 Constructor += " *desc";
3894
3895 if (BlockDeclRefs.size()) {
3896 // Output all "by copy" declarations.
3897 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3898 E = BlockByCopyDecls.end(); I != E; ++I) {
3899 S += " ";
3900 std::string FieldName = (*I)->getNameAsString();
3901 std::string ArgName = "_" + FieldName;
3902 // Handle nested closure invocation. For example:
3903 //
3904 // void (^myImportedBlock)(void);
3905 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3906 //
3907 // void (^anotherBlock)(void);
3908 // anotherBlock = ^(void) {
3909 // myImportedBlock(); // import and invoke the closure
3910 // };
3911 //
3912 if (isTopLevelBlockPointerType((*I)->getType())) {
3913 S += "struct __block_impl *";
3914 Constructor += ", void *" + ArgName;
3915 } else {
3916 QualType QT = (*I)->getType();
3917 if (HasLocalVariableExternalStorage(*I))
3918 QT = Context->getPointerType(QT);
3919 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3920 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3921 Constructor += ", " + ArgName;
3922 }
3923 S += FieldName + ";\n";
3924 }
3925 // Output all "by ref" declarations.
3926 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3927 E = BlockByRefDecls.end(); I != E; ++I) {
3928 S += " ";
3929 std::string FieldName = (*I)->getNameAsString();
3930 std::string ArgName = "_" + FieldName;
3931 {
3932 std::string TypeString;
3933 RewriteByRefString(TypeString, FieldName, (*I));
3934 TypeString += " *";
3935 FieldName = TypeString + FieldName;
3936 ArgName = TypeString + ArgName;
3937 Constructor += ", " + ArgName;
3938 }
3939 S += FieldName + "; // by ref\n";
3940 }
3941 // Finish writing the constructor.
3942 Constructor += ", int flags=0)";
3943 // Initialize all "by copy" arguments.
3944 bool firsTime = true;
3945 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3946 E = BlockByCopyDecls.end(); I != E; ++I) {
3947 std::string Name = (*I)->getNameAsString();
3948 if (firsTime) {
3949 Constructor += " : ";
3950 firsTime = false;
3951 }
3952 else
3953 Constructor += ", ";
3954 if (isTopLevelBlockPointerType((*I)->getType()))
3955 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3956 else
3957 Constructor += Name + "(_" + Name + ")";
3958 }
3959 // Initialize all "by ref" arguments.
3960 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3961 E = BlockByRefDecls.end(); I != E; ++I) {
3962 std::string Name = (*I)->getNameAsString();
3963 if (firsTime) {
3964 Constructor += " : ";
3965 firsTime = false;
3966 }
3967 else
3968 Constructor += ", ";
3969 Constructor += Name + "(_" + Name + "->__forwarding)";
3970 }
3971
3972 Constructor += " {\n";
3973 if (GlobalVarDecl)
3974 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3975 else
3976 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3977 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3978
3979 Constructor += " Desc = desc;\n";
3980 } else {
3981 // Finish writing the constructor.
3982 Constructor += ", int flags=0) {\n";
3983 if (GlobalVarDecl)
3984 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3985 else
3986 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3987 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3988 Constructor += " Desc = desc;\n";
3989 }
3990 Constructor += " ";
3991 Constructor += "}\n";
3992 S += Constructor;
3993 S += "};\n";
3994 return S;
3995}
3996
3997std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3998 std::string ImplTag, int i,
3999 StringRef FunName,
4000 unsigned hasCopy) {
4001 std::string S = "\nstatic struct " + DescTag;
4002
4003 S += " {\n unsigned long reserved;\n";
4004 S += " unsigned long Block_size;\n";
4005 if (hasCopy) {
4006 S += " void (*copy)(struct ";
4007 S += ImplTag; S += "*, struct ";
4008 S += ImplTag; S += "*);\n";
4009
4010 S += " void (*dispose)(struct ";
4011 S += ImplTag; S += "*);\n";
4012 }
4013 S += "} ";
4014
4015 S += DescTag + "_DATA = { 0, sizeof(struct ";
4016 S += ImplTag + ")";
4017 if (hasCopy) {
4018 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4019 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4020 }
4021 S += "};\n";
4022 return S;
4023}
4024
4025void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4026 StringRef FunName) {
4027 // Insert declaration for the function in which block literal is used.
4028 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
4029 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4030 bool RewriteSC = (GlobalVarDecl &&
4031 !Blocks.empty() &&
4032 GlobalVarDecl->getStorageClass() == SC_Static &&
4033 GlobalVarDecl->getType().getCVRQualifiers());
4034 if (RewriteSC) {
4035 std::string SC(" void __");
4036 SC += GlobalVarDecl->getNameAsString();
4037 SC += "() {}";
4038 InsertText(FunLocStart, SC);
4039 }
4040
4041 // Insert closures that were part of the function.
4042 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4043 CollectBlockDeclRefInfo(Blocks[i]);
4044 // Need to copy-in the inner copied-in variables not actually used in this
4045 // block.
4046 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004047 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004048 ValueDecl *VD = Exp->getDecl();
4049 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004050 if (!VD->hasAttr<BlocksAttr>()) {
4051 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4052 BlockByCopyDeclsPtrSet.insert(VD);
4053 BlockByCopyDecls.push_back(VD);
4054 }
4055 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004056 }
John McCallf4b88a42012-03-10 09:33:50 +00004057
4058 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004059 BlockByRefDeclsPtrSet.insert(VD);
4060 BlockByRefDecls.push_back(VD);
4061 }
John McCallf4b88a42012-03-10 09:33:50 +00004062
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004063 // imported objects in the inner blocks not used in the outer
4064 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004065 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004066 VD->getType()->isBlockPointerType())
4067 ImportedBlockDecls.insert(VD);
4068 }
4069
4070 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4071 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4072
4073 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4074
4075 InsertText(FunLocStart, CI);
4076
4077 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4078
4079 InsertText(FunLocStart, CF);
4080
4081 if (ImportedBlockDecls.size()) {
4082 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4083 InsertText(FunLocStart, HF);
4084 }
4085 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4086 ImportedBlockDecls.size() > 0);
4087 InsertText(FunLocStart, BD);
4088
4089 BlockDeclRefs.clear();
4090 BlockByRefDecls.clear();
4091 BlockByRefDeclsPtrSet.clear();
4092 BlockByCopyDecls.clear();
4093 BlockByCopyDeclsPtrSet.clear();
4094 ImportedBlockDecls.clear();
4095 }
4096 if (RewriteSC) {
4097 // Must insert any 'const/volatile/static here. Since it has been
4098 // removed as result of rewriting of block literals.
4099 std::string SC;
4100 if (GlobalVarDecl->getStorageClass() == SC_Static)
4101 SC = "static ";
4102 if (GlobalVarDecl->getType().isConstQualified())
4103 SC += "const ";
4104 if (GlobalVarDecl->getType().isVolatileQualified())
4105 SC += "volatile ";
4106 if (GlobalVarDecl->getType().isRestrictQualified())
4107 SC += "restrict ";
4108 InsertText(FunLocStart, SC);
4109 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004110 if (GlobalConstructionExp) {
4111 // extra fancy dance for global literal expression.
4112
4113 // Always the latest block expression on the block stack.
4114 std::string Tag = "__";
4115 Tag += FunName;
4116 Tag += "_block_impl_";
4117 Tag += utostr(Blocks.size()-1);
4118 std::string globalBuf = "static ";
4119 globalBuf += Tag; globalBuf += " ";
4120 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004121
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004122 llvm::raw_string_ostream constructorExprBuf(SStr);
4123 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4124 PrintingPolicy(LangOpts));
4125 globalBuf += constructorExprBuf.str();
4126 globalBuf += ";\n";
4127 InsertText(FunLocStart, globalBuf);
4128 GlobalConstructionExp = 0;
4129 }
4130
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004131 Blocks.clear();
4132 InnerDeclRefsCount.clear();
4133 InnerDeclRefs.clear();
4134 RewrittenBlockExprs.clear();
4135}
4136
4137void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4138 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
4139 StringRef FuncName = FD->getName();
4140
4141 SynthesizeBlockLiterals(FunLocStart, FuncName);
4142}
4143
4144static void BuildUniqueMethodName(std::string &Name,
4145 ObjCMethodDecl *MD) {
4146 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4147 Name = IFace->getName();
4148 Name += "__" + MD->getSelector().getAsString();
4149 // Convert colons to underscores.
4150 std::string::size_type loc = 0;
4151 while ((loc = Name.find(":", loc)) != std::string::npos)
4152 Name.replace(loc, 1, "_");
4153}
4154
4155void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4156 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4157 //SourceLocation FunLocStart = MD->getLocStart();
4158 SourceLocation FunLocStart = MD->getLocStart();
4159 std::string FuncName;
4160 BuildUniqueMethodName(FuncName, MD);
4161 SynthesizeBlockLiterals(FunLocStart, FuncName);
4162}
4163
4164void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4165 for (Stmt::child_range CI = S->children(); CI; ++CI)
4166 if (*CI) {
4167 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4168 GetBlockDeclRefExprs(CBE->getBody());
4169 else
4170 GetBlockDeclRefExprs(*CI);
4171 }
4172 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004173 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4174 if (DRE->refersToEnclosingLocal() &&
4175 HasLocalVariableExternalStorage(DRE->getDecl())) {
4176 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004177 }
4178
4179 return;
4180}
4181
4182void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004183 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004184 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4185 for (Stmt::child_range CI = S->children(); CI; ++CI)
4186 if (*CI) {
4187 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4188 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4189 GetInnerBlockDeclRefExprs(CBE->getBody(),
4190 InnerBlockDeclRefs,
4191 InnerContexts);
4192 }
4193 else
4194 GetInnerBlockDeclRefExprs(*CI,
4195 InnerBlockDeclRefs,
4196 InnerContexts);
4197
4198 }
4199 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004200 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4201 if (DRE->refersToEnclosingLocal()) {
4202 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4203 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4204 InnerBlockDeclRefs.push_back(DRE);
4205 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4206 if (Var->isFunctionOrMethodVarDecl())
4207 ImportedLocalExternalDecls.insert(Var);
4208 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004209 }
4210
4211 return;
4212}
4213
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004214/// convertObjCTypeToCStyleType - This routine converts such objc types
4215/// as qualified objects, and blocks to their closest c/c++ types that
4216/// it can. It returns true if input type was modified.
4217bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4218 QualType oldT = T;
4219 convertBlockPointerToFunctionPointer(T);
4220 if (T->isFunctionPointerType()) {
4221 QualType PointeeTy;
4222 if (const PointerType* PT = T->getAs<PointerType>()) {
4223 PointeeTy = PT->getPointeeType();
4224 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4225 T = convertFunctionTypeOfBlocks(FT);
4226 T = Context->getPointerType(T);
4227 }
4228 }
4229 }
4230
4231 convertToUnqualifiedObjCType(T);
4232 return T != oldT;
4233}
4234
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004235/// convertFunctionTypeOfBlocks - This routine converts a function type
4236/// whose result type may be a block pointer or whose argument type(s)
4237/// might be block pointers to an equivalent function type replacing
4238/// all block pointers to function pointers.
4239QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4240 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4241 // FTP will be null for closures that don't take arguments.
4242 // Generate a funky cast.
4243 SmallVector<QualType, 8> ArgTypes;
4244 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004245 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004246
4247 if (FTP) {
4248 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4249 E = FTP->arg_type_end(); I && (I != E); ++I) {
4250 QualType t = *I;
4251 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004252 if (convertObjCTypeToCStyleType(t))
4253 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004254 ArgTypes.push_back(t);
4255 }
4256 }
4257 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004258 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004259 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4260 else FuncType = QualType(FT, 0);
4261 return FuncType;
4262}
4263
4264Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4265 // Navigate to relevant type information.
4266 const BlockPointerType *CPT = 0;
4267
4268 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4269 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004270 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4271 CPT = MExpr->getType()->getAs<BlockPointerType>();
4272 }
4273 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4274 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4275 }
4276 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4277 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4278 else if (const ConditionalOperator *CEXPR =
4279 dyn_cast<ConditionalOperator>(BlockExp)) {
4280 Expr *LHSExp = CEXPR->getLHS();
4281 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4282 Expr *RHSExp = CEXPR->getRHS();
4283 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4284 Expr *CONDExp = CEXPR->getCond();
4285 ConditionalOperator *CondExpr =
4286 new (Context) ConditionalOperator(CONDExp,
4287 SourceLocation(), cast<Expr>(LHSStmt),
4288 SourceLocation(), cast<Expr>(RHSStmt),
4289 Exp->getType(), VK_RValue, OK_Ordinary);
4290 return CondExpr;
4291 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4292 CPT = IRE->getType()->getAs<BlockPointerType>();
4293 } else if (const PseudoObjectExpr *POE
4294 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4295 CPT = POE->getType()->castAs<BlockPointerType>();
4296 } else {
4297 assert(1 && "RewriteBlockClass: Bad type");
4298 }
4299 assert(CPT && "RewriteBlockClass: Bad type");
4300 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4301 assert(FT && "RewriteBlockClass: Bad type");
4302 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4303 // FTP will be null for closures that don't take arguments.
4304
4305 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4306 SourceLocation(), SourceLocation(),
4307 &Context->Idents.get("__block_impl"));
4308 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4309
4310 // Generate a funky cast.
4311 SmallVector<QualType, 8> ArgTypes;
4312
4313 // Push the block argument type.
4314 ArgTypes.push_back(PtrBlock);
4315 if (FTP) {
4316 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4317 E = FTP->arg_type_end(); I && (I != E); ++I) {
4318 QualType t = *I;
4319 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4320 if (!convertBlockPointerToFunctionPointer(t))
4321 convertToUnqualifiedObjCType(t);
4322 ArgTypes.push_back(t);
4323 }
4324 }
4325 // Now do the pointer to function cast.
4326 QualType PtrToFuncCastType
4327 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4328
4329 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4330
4331 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4332 CK_BitCast,
4333 const_cast<Expr*>(BlockExp));
4334 // Don't forget the parens to enforce the proper binding.
4335 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4336 BlkCast);
4337 //PE->dump();
4338
4339 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4340 SourceLocation(),
4341 &Context->Idents.get("FuncPtr"),
4342 Context->VoidPtrTy, 0,
4343 /*BitWidth=*/0, /*Mutable=*/true,
4344 /*HasInit=*/false);
4345 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4346 FD->getType(), VK_LValue,
4347 OK_Ordinary);
4348
4349
4350 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4351 CK_BitCast, ME);
4352 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4353
4354 SmallVector<Expr*, 8> BlkExprs;
4355 // Add the implicit argument.
4356 BlkExprs.push_back(BlkCast);
4357 // Add the user arguments.
4358 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4359 E = Exp->arg_end(); I != E; ++I) {
4360 BlkExprs.push_back(*I);
4361 }
4362 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4363 BlkExprs.size(),
4364 Exp->getType(), VK_RValue,
4365 SourceLocation());
4366 return CE;
4367}
4368
4369// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004370// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004371// For example:
4372//
4373// int main() {
4374// __block Foo *f;
4375// __block int i;
4376//
4377// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004378// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004379// i = 77;
4380// };
4381//}
John McCallf4b88a42012-03-10 09:33:50 +00004382Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004383 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4384 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004385 ValueDecl *VD = DeclRefExp->getDecl();
4386 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004387
4388 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4389 SourceLocation(),
4390 &Context->Idents.get("__forwarding"),
4391 Context->VoidPtrTy, 0,
4392 /*BitWidth=*/0, /*Mutable=*/true,
4393 /*HasInit=*/false);
4394 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4395 FD, SourceLocation(),
4396 FD->getType(), VK_LValue,
4397 OK_Ordinary);
4398
4399 StringRef Name = VD->getName();
4400 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4401 &Context->Idents.get(Name),
4402 Context->VoidPtrTy, 0,
4403 /*BitWidth=*/0, /*Mutable=*/true,
4404 /*HasInit=*/false);
4405 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4406 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4407
4408
4409
4410 // Need parens to enforce precedence.
4411 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4412 DeclRefExp->getExprLoc(),
4413 ME);
4414 ReplaceStmt(DeclRefExp, PE);
4415 return PE;
4416}
4417
4418// Rewrites the imported local variable V with external storage
4419// (static, extern, etc.) as *V
4420//
4421Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4422 ValueDecl *VD = DRE->getDecl();
4423 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4424 if (!ImportedLocalExternalDecls.count(Var))
4425 return DRE;
4426 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4427 VK_LValue, OK_Ordinary,
4428 DRE->getLocation());
4429 // Need parens to enforce precedence.
4430 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4431 Exp);
4432 ReplaceStmt(DRE, PE);
4433 return PE;
4434}
4435
4436void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4437 SourceLocation LocStart = CE->getLParenLoc();
4438 SourceLocation LocEnd = CE->getRParenLoc();
4439
4440 // Need to avoid trying to rewrite synthesized casts.
4441 if (LocStart.isInvalid())
4442 return;
4443 // Need to avoid trying to rewrite casts contained in macros.
4444 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4445 return;
4446
4447 const char *startBuf = SM->getCharacterData(LocStart);
4448 const char *endBuf = SM->getCharacterData(LocEnd);
4449 QualType QT = CE->getType();
4450 const Type* TypePtr = QT->getAs<Type>();
4451 if (isa<TypeOfExprType>(TypePtr)) {
4452 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4453 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4454 std::string TypeAsString = "(";
4455 RewriteBlockPointerType(TypeAsString, QT);
4456 TypeAsString += ")";
4457 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4458 return;
4459 }
4460 // advance the location to startArgList.
4461 const char *argPtr = startBuf;
4462
4463 while (*argPtr++ && (argPtr < endBuf)) {
4464 switch (*argPtr) {
4465 case '^':
4466 // Replace the '^' with '*'.
4467 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4468 ReplaceText(LocStart, 1, "*");
4469 break;
4470 }
4471 }
4472 return;
4473}
4474
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004475void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4476 CastKind CastKind = IC->getCastKind();
4477
4478 if (CastKind == CK_BlockPointerToObjCPointerCast) {
4479 CStyleCastExpr * CastExpr =
4480 NoTypeInfoCStyleCastExpr(Context, IC->getType(), CK_BitCast, IC);
4481 ReplaceStmt(IC, CastExpr);
4482 }
4483 else if (CastKind == CK_AnyPointerToBlockPointerCast) {
4484 QualType BlockT = IC->getType();
4485 (void)convertBlockPointerToFunctionPointer(BlockT);
4486 CStyleCastExpr * CastExpr =
4487 NoTypeInfoCStyleCastExpr(Context, BlockT, CK_BitCast, IC);
4488 ReplaceStmt(IC, CastExpr);
4489 }
4490 return;
4491}
4492
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004493void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4494 SourceLocation DeclLoc = FD->getLocation();
4495 unsigned parenCount = 0;
4496
4497 // We have 1 or more arguments that have closure pointers.
4498 const char *startBuf = SM->getCharacterData(DeclLoc);
4499 const char *startArgList = strchr(startBuf, '(');
4500
4501 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4502
4503 parenCount++;
4504 // advance the location to startArgList.
4505 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4506 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4507
4508 const char *argPtr = startArgList;
4509
4510 while (*argPtr++ && parenCount) {
4511 switch (*argPtr) {
4512 case '^':
4513 // Replace the '^' with '*'.
4514 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4515 ReplaceText(DeclLoc, 1, "*");
4516 break;
4517 case '(':
4518 parenCount++;
4519 break;
4520 case ')':
4521 parenCount--;
4522 break;
4523 }
4524 }
4525 return;
4526}
4527
4528bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4529 const FunctionProtoType *FTP;
4530 const PointerType *PT = QT->getAs<PointerType>();
4531 if (PT) {
4532 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4533 } else {
4534 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4535 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4536 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4537 }
4538 if (FTP) {
4539 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4540 E = FTP->arg_type_end(); I != E; ++I)
4541 if (isTopLevelBlockPointerType(*I))
4542 return true;
4543 }
4544 return false;
4545}
4546
4547bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4548 const FunctionProtoType *FTP;
4549 const PointerType *PT = QT->getAs<PointerType>();
4550 if (PT) {
4551 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4552 } else {
4553 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4554 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4555 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4556 }
4557 if (FTP) {
4558 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4559 E = FTP->arg_type_end(); I != E; ++I) {
4560 if ((*I)->isObjCQualifiedIdType())
4561 return true;
4562 if ((*I)->isObjCObjectPointerType() &&
4563 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4564 return true;
4565 }
4566
4567 }
4568 return false;
4569}
4570
4571void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4572 const char *&RParen) {
4573 const char *argPtr = strchr(Name, '(');
4574 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4575
4576 LParen = argPtr; // output the start.
4577 argPtr++; // skip past the left paren.
4578 unsigned parenCount = 1;
4579
4580 while (*argPtr && parenCount) {
4581 switch (*argPtr) {
4582 case '(': parenCount++; break;
4583 case ')': parenCount--; break;
4584 default: break;
4585 }
4586 if (parenCount) argPtr++;
4587 }
4588 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4589 RParen = argPtr; // output the end
4590}
4591
4592void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4593 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4594 RewriteBlockPointerFunctionArgs(FD);
4595 return;
4596 }
4597 // Handle Variables and Typedefs.
4598 SourceLocation DeclLoc = ND->getLocation();
4599 QualType DeclT;
4600 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4601 DeclT = VD->getType();
4602 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4603 DeclT = TDD->getUnderlyingType();
4604 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4605 DeclT = FD->getType();
4606 else
4607 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4608
4609 const char *startBuf = SM->getCharacterData(DeclLoc);
4610 const char *endBuf = startBuf;
4611 // scan backward (from the decl location) for the end of the previous decl.
4612 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4613 startBuf--;
4614 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4615 std::string buf;
4616 unsigned OrigLength=0;
4617 // *startBuf != '^' if we are dealing with a pointer to function that
4618 // may take block argument types (which will be handled below).
4619 if (*startBuf == '^') {
4620 // Replace the '^' with '*', computing a negative offset.
4621 buf = '*';
4622 startBuf++;
4623 OrigLength++;
4624 }
4625 while (*startBuf != ')') {
4626 buf += *startBuf;
4627 startBuf++;
4628 OrigLength++;
4629 }
4630 buf += ')';
4631 OrigLength++;
4632
4633 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4634 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4635 // Replace the '^' with '*' for arguments.
4636 // Replace id<P> with id/*<>*/
4637 DeclLoc = ND->getLocation();
4638 startBuf = SM->getCharacterData(DeclLoc);
4639 const char *argListBegin, *argListEnd;
4640 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4641 while (argListBegin < argListEnd) {
4642 if (*argListBegin == '^')
4643 buf += '*';
4644 else if (*argListBegin == '<') {
4645 buf += "/*";
4646 buf += *argListBegin++;
4647 OrigLength++;;
4648 while (*argListBegin != '>') {
4649 buf += *argListBegin++;
4650 OrigLength++;
4651 }
4652 buf += *argListBegin;
4653 buf += "*/";
4654 }
4655 else
4656 buf += *argListBegin;
4657 argListBegin++;
4658 OrigLength++;
4659 }
4660 buf += ')';
4661 OrigLength++;
4662 }
4663 ReplaceText(Start, OrigLength, buf);
4664
4665 return;
4666}
4667
4668
4669/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4670/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4671/// struct Block_byref_id_object *src) {
4672/// _Block_object_assign (&_dest->object, _src->object,
4673/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4674/// [|BLOCK_FIELD_IS_WEAK]) // object
4675/// _Block_object_assign(&_dest->object, _src->object,
4676/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4677/// [|BLOCK_FIELD_IS_WEAK]) // block
4678/// }
4679/// And:
4680/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4681/// _Block_object_dispose(_src->object,
4682/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4683/// [|BLOCK_FIELD_IS_WEAK]) // object
4684/// _Block_object_dispose(_src->object,
4685/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4686/// [|BLOCK_FIELD_IS_WEAK]) // block
4687/// }
4688
4689std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4690 int flag) {
4691 std::string S;
4692 if (CopyDestroyCache.count(flag))
4693 return S;
4694 CopyDestroyCache.insert(flag);
4695 S = "static void __Block_byref_id_object_copy_";
4696 S += utostr(flag);
4697 S += "(void *dst, void *src) {\n";
4698
4699 // offset into the object pointer is computed as:
4700 // void * + void* + int + int + void* + void *
4701 unsigned IntSize =
4702 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4703 unsigned VoidPtrSize =
4704 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4705
4706 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4707 S += " _Block_object_assign((char*)dst + ";
4708 S += utostr(offset);
4709 S += ", *(void * *) ((char*)src + ";
4710 S += utostr(offset);
4711 S += "), ";
4712 S += utostr(flag);
4713 S += ");\n}\n";
4714
4715 S += "static void __Block_byref_id_object_dispose_";
4716 S += utostr(flag);
4717 S += "(void *src) {\n";
4718 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4719 S += utostr(offset);
4720 S += "), ";
4721 S += utostr(flag);
4722 S += ");\n}\n";
4723 return S;
4724}
4725
4726/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4727/// the declaration into:
4728/// struct __Block_byref_ND {
4729/// void *__isa; // NULL for everything except __weak pointers
4730/// struct __Block_byref_ND *__forwarding;
4731/// int32_t __flags;
4732/// int32_t __size;
4733/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4734/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4735/// typex ND;
4736/// };
4737///
4738/// It then replaces declaration of ND variable with:
4739/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4740/// __size=sizeof(struct __Block_byref_ND),
4741/// ND=initializer-if-any};
4742///
4743///
4744void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4745 // Insert declaration for the function in which block literal is
4746 // used.
4747 if (CurFunctionDeclToDeclareForBlock)
4748 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4749 int flag = 0;
4750 int isa = 0;
4751 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4752 if (DeclLoc.isInvalid())
4753 // If type location is missing, it is because of missing type (a warning).
4754 // Use variable's location which is good for this case.
4755 DeclLoc = ND->getLocation();
4756 const char *startBuf = SM->getCharacterData(DeclLoc);
4757 SourceLocation X = ND->getLocEnd();
4758 X = SM->getExpansionLoc(X);
4759 const char *endBuf = SM->getCharacterData(X);
4760 std::string Name(ND->getNameAsString());
4761 std::string ByrefType;
4762 RewriteByRefString(ByrefType, Name, ND, true);
4763 ByrefType += " {\n";
4764 ByrefType += " void *__isa;\n";
4765 RewriteByRefString(ByrefType, Name, ND);
4766 ByrefType += " *__forwarding;\n";
4767 ByrefType += " int __flags;\n";
4768 ByrefType += " int __size;\n";
4769 // Add void *__Block_byref_id_object_copy;
4770 // void *__Block_byref_id_object_dispose; if needed.
4771 QualType Ty = ND->getType();
4772 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4773 if (HasCopyAndDispose) {
4774 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4775 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4776 }
4777
4778 QualType T = Ty;
4779 (void)convertBlockPointerToFunctionPointer(T);
4780 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4781
4782 ByrefType += " " + Name + ";\n";
4783 ByrefType += "};\n";
4784 // Insert this type in global scope. It is needed by helper function.
4785 SourceLocation FunLocStart;
4786 if (CurFunctionDef)
4787 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4788 else {
4789 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4790 FunLocStart = CurMethodDef->getLocStart();
4791 }
4792 InsertText(FunLocStart, ByrefType);
4793 if (Ty.isObjCGCWeak()) {
4794 flag |= BLOCK_FIELD_IS_WEAK;
4795 isa = 1;
4796 }
4797
4798 if (HasCopyAndDispose) {
4799 flag = BLOCK_BYREF_CALLER;
4800 QualType Ty = ND->getType();
4801 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4802 if (Ty->isBlockPointerType())
4803 flag |= BLOCK_FIELD_IS_BLOCK;
4804 else
4805 flag |= BLOCK_FIELD_IS_OBJECT;
4806 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4807 if (!HF.empty())
4808 InsertText(FunLocStart, HF);
4809 }
4810
4811 // struct __Block_byref_ND ND =
4812 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4813 // initializer-if-any};
4814 bool hasInit = (ND->getInit() != 0);
4815 unsigned flags = 0;
4816 if (HasCopyAndDispose)
4817 flags |= BLOCK_HAS_COPY_DISPOSE;
4818 Name = ND->getNameAsString();
4819 ByrefType.clear();
4820 RewriteByRefString(ByrefType, Name, ND);
4821 std::string ForwardingCastType("(");
4822 ForwardingCastType += ByrefType + " *)";
4823 if (!hasInit) {
4824 ByrefType += " " + Name + " = {(void*)";
4825 ByrefType += utostr(isa);
4826 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4827 ByrefType += utostr(flags);
4828 ByrefType += ", ";
4829 ByrefType += "sizeof(";
4830 RewriteByRefString(ByrefType, Name, ND);
4831 ByrefType += ")";
4832 if (HasCopyAndDispose) {
4833 ByrefType += ", __Block_byref_id_object_copy_";
4834 ByrefType += utostr(flag);
4835 ByrefType += ", __Block_byref_id_object_dispose_";
4836 ByrefType += utostr(flag);
4837 }
4838 ByrefType += "};\n";
4839 unsigned nameSize = Name.size();
4840 // for block or function pointer declaration. Name is aleady
4841 // part of the declaration.
4842 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4843 nameSize = 1;
4844 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4845 }
4846 else {
4847 SourceLocation startLoc;
4848 Expr *E = ND->getInit();
4849 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4850 startLoc = ECE->getLParenLoc();
4851 else
4852 startLoc = E->getLocStart();
4853 startLoc = SM->getExpansionLoc(startLoc);
4854 endBuf = SM->getCharacterData(startLoc);
4855 ByrefType += " " + Name;
4856 ByrefType += " = {(void*)";
4857 ByrefType += utostr(isa);
4858 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4859 ByrefType += utostr(flags);
4860 ByrefType += ", ";
4861 ByrefType += "sizeof(";
4862 RewriteByRefString(ByrefType, Name, ND);
4863 ByrefType += "), ";
4864 if (HasCopyAndDispose) {
4865 ByrefType += "__Block_byref_id_object_copy_";
4866 ByrefType += utostr(flag);
4867 ByrefType += ", __Block_byref_id_object_dispose_";
4868 ByrefType += utostr(flag);
4869 ByrefType += ", ";
4870 }
4871 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4872
4873 // Complete the newly synthesized compound expression by inserting a right
4874 // curly brace before the end of the declaration.
4875 // FIXME: This approach avoids rewriting the initializer expression. It
4876 // also assumes there is only one declarator. For example, the following
4877 // isn't currently supported by this routine (in general):
4878 //
4879 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4880 //
4881 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4882 const char *semiBuf = strchr(startInitializerBuf, ';');
4883 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4884 SourceLocation semiLoc =
4885 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4886
4887 InsertText(semiLoc, "}");
4888 }
4889 return;
4890}
4891
4892void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4893 // Add initializers for any closure decl refs.
4894 GetBlockDeclRefExprs(Exp->getBody());
4895 if (BlockDeclRefs.size()) {
4896 // Unique all "by copy" declarations.
4897 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004898 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004899 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4900 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4901 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4902 }
4903 }
4904 // Unique all "by ref" declarations.
4905 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004906 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004907 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4908 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4909 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4910 }
4911 }
4912 // Find any imported blocks...they will need special attention.
4913 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004914 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004915 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4916 BlockDeclRefs[i]->getType()->isBlockPointerType())
4917 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4918 }
4919}
4920
4921FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4922 IdentifierInfo *ID = &Context->Idents.get(name);
4923 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4924 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4925 SourceLocation(), ID, FType, 0, SC_Extern,
4926 SC_None, false, false);
4927}
4928
4929Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004930 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004931
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004932 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004933
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004934 Blocks.push_back(Exp);
4935
4936 CollectBlockDeclRefInfo(Exp);
4937
4938 // Add inner imported variables now used in current block.
4939 int countOfInnerDecls = 0;
4940 if (!InnerBlockDeclRefs.empty()) {
4941 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004942 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004943 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004944 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004945 // We need to save the copied-in variables in nested
4946 // blocks because it is needed at the end for some of the API generations.
4947 // See SynthesizeBlockLiterals routine.
4948 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4949 BlockDeclRefs.push_back(Exp);
4950 BlockByCopyDeclsPtrSet.insert(VD);
4951 BlockByCopyDecls.push_back(VD);
4952 }
John McCallf4b88a42012-03-10 09:33:50 +00004953 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004954 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4955 BlockDeclRefs.push_back(Exp);
4956 BlockByRefDeclsPtrSet.insert(VD);
4957 BlockByRefDecls.push_back(VD);
4958 }
4959 }
4960 // Find any imported blocks...they will need special attention.
4961 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004962 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004963 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4964 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4965 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4966 }
4967 InnerDeclRefsCount.push_back(countOfInnerDecls);
4968
4969 std::string FuncName;
4970
4971 if (CurFunctionDef)
4972 FuncName = CurFunctionDef->getNameAsString();
4973 else if (CurMethodDef)
4974 BuildUniqueMethodName(FuncName, CurMethodDef);
4975 else if (GlobalVarDecl)
4976 FuncName = std::string(GlobalVarDecl->getNameAsString());
4977
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004978 bool GlobalBlockExpr =
4979 block->getDeclContext()->getRedeclContext()->isFileContext();
4980
4981 if (GlobalBlockExpr && !GlobalVarDecl) {
4982 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4983 GlobalBlockExpr = false;
4984 }
4985
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004986 std::string BlockNumber = utostr(Blocks.size()-1);
4987
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004988 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4989
4990 // Get a pointer to the function type so we can cast appropriately.
4991 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4992 QualType FType = Context->getPointerType(BFT);
4993
4994 FunctionDecl *FD;
4995 Expr *NewRep;
4996
4997 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004998 std::string Tag;
4999
5000 if (GlobalBlockExpr)
5001 Tag = "__global_";
5002 else
5003 Tag = "__";
5004 Tag += FuncName + "_block_impl_" + BlockNumber;
5005
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005006 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005007 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005008 SourceLocation());
5009
5010 SmallVector<Expr*, 4> InitExprs;
5011
5012 // Initialize the block function.
5013 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005014 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5015 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005016 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5017 CK_BitCast, Arg);
5018 InitExprs.push_back(castExpr);
5019
5020 // Initialize the block descriptor.
5021 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5022
5023 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5024 SourceLocation(), SourceLocation(),
5025 &Context->Idents.get(DescData.c_str()),
5026 Context->VoidPtrTy, 0,
5027 SC_Static, SC_None);
5028 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005029 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005030 Context->VoidPtrTy,
5031 VK_LValue,
5032 SourceLocation()),
5033 UO_AddrOf,
5034 Context->getPointerType(Context->VoidPtrTy),
5035 VK_RValue, OK_Ordinary,
5036 SourceLocation());
5037 InitExprs.push_back(DescRefExpr);
5038
5039 // Add initializers for any closure decl refs.
5040 if (BlockDeclRefs.size()) {
5041 Expr *Exp;
5042 // Output all "by copy" declarations.
5043 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5044 E = BlockByCopyDecls.end(); I != E; ++I) {
5045 if (isObjCType((*I)->getType())) {
5046 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5047 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005048 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5049 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005050 if (HasLocalVariableExternalStorage(*I)) {
5051 QualType QT = (*I)->getType();
5052 QT = Context->getPointerType(QT);
5053 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5054 OK_Ordinary, SourceLocation());
5055 }
5056 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5057 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005058 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5059 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005060 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5061 CK_BitCast, Arg);
5062 } else {
5063 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005064 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5065 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005066 if (HasLocalVariableExternalStorage(*I)) {
5067 QualType QT = (*I)->getType();
5068 QT = Context->getPointerType(QT);
5069 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5070 OK_Ordinary, SourceLocation());
5071 }
5072
5073 }
5074 InitExprs.push_back(Exp);
5075 }
5076 // Output all "by ref" declarations.
5077 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5078 E = BlockByRefDecls.end(); I != E; ++I) {
5079 ValueDecl *ND = (*I);
5080 std::string Name(ND->getNameAsString());
5081 std::string RecName;
5082 RewriteByRefString(RecName, Name, ND, true);
5083 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5084 + sizeof("struct"));
5085 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5086 SourceLocation(), SourceLocation(),
5087 II);
5088 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5089 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5090
5091 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005092 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005093 SourceLocation());
5094 bool isNestedCapturedVar = false;
5095 if (block)
5096 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5097 ce = block->capture_end(); ci != ce; ++ci) {
5098 const VarDecl *variable = ci->getVariable();
5099 if (variable == ND && ci->isNested()) {
5100 assert (ci->isByRef() &&
5101 "SynthBlockInitExpr - captured block variable is not byref");
5102 isNestedCapturedVar = true;
5103 break;
5104 }
5105 }
5106 // captured nested byref variable has its address passed. Do not take
5107 // its address again.
5108 if (!isNestedCapturedVar)
5109 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5110 Context->getPointerType(Exp->getType()),
5111 VK_RValue, OK_Ordinary, SourceLocation());
5112 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5113 InitExprs.push_back(Exp);
5114 }
5115 }
5116 if (ImportedBlockDecls.size()) {
5117 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5118 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5119 unsigned IntSize =
5120 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5121 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5122 Context->IntTy, SourceLocation());
5123 InitExprs.push_back(FlagExp);
5124 }
5125 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5126 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005127
5128 if (GlobalBlockExpr) {
5129 assert (GlobalConstructionExp == 0 &&
5130 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5131 GlobalConstructionExp = NewRep;
5132 NewRep = DRE;
5133 }
5134
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005135 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5136 Context->getPointerType(NewRep->getType()),
5137 VK_RValue, OK_Ordinary, SourceLocation());
5138 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5139 NewRep);
5140 BlockDeclRefs.clear();
5141 BlockByRefDecls.clear();
5142 BlockByRefDeclsPtrSet.clear();
5143 BlockByCopyDecls.clear();
5144 BlockByCopyDeclsPtrSet.clear();
5145 ImportedBlockDecls.clear();
5146 return NewRep;
5147}
5148
5149bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5150 if (const ObjCForCollectionStmt * CS =
5151 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5152 return CS->getElement() == DS;
5153 return false;
5154}
5155
5156//===----------------------------------------------------------------------===//
5157// Function Body / Expression rewriting
5158//===----------------------------------------------------------------------===//
5159
5160Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5161 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5162 isa<DoStmt>(S) || isa<ForStmt>(S))
5163 Stmts.push_back(S);
5164 else if (isa<ObjCForCollectionStmt>(S)) {
5165 Stmts.push_back(S);
5166 ObjCBcLabelNo.push_back(++BcLabelCount);
5167 }
5168
5169 // Pseudo-object operations and ivar references need special
5170 // treatment because we're going to recursively rewrite them.
5171 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5172 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5173 return RewritePropertyOrImplicitSetter(PseudoOp);
5174 } else {
5175 return RewritePropertyOrImplicitGetter(PseudoOp);
5176 }
5177 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5178 return RewriteObjCIvarRefExpr(IvarRefExpr);
5179 }
5180
5181 SourceRange OrigStmtRange = S->getSourceRange();
5182
5183 // Perform a bottom up rewrite of all children.
5184 for (Stmt::child_range CI = S->children(); CI; ++CI)
5185 if (*CI) {
5186 Stmt *childStmt = (*CI);
5187 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5188 if (newStmt) {
5189 *CI = newStmt;
5190 }
5191 }
5192
5193 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005194 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005195 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5196 InnerContexts.insert(BE->getBlockDecl());
5197 ImportedLocalExternalDecls.clear();
5198 GetInnerBlockDeclRefExprs(BE->getBody(),
5199 InnerBlockDeclRefs, InnerContexts);
5200 // Rewrite the block body in place.
5201 Stmt *SaveCurrentBody = CurrentBody;
5202 CurrentBody = BE->getBody();
5203 PropParentMap = 0;
5204 // block literal on rhs of a property-dot-sytax assignment
5205 // must be replaced by its synthesize ast so getRewrittenText
5206 // works as expected. In this case, what actually ends up on RHS
5207 // is the blockTranscribed which is the helper function for the
5208 // block literal; as in: self.c = ^() {[ace ARR];};
5209 bool saveDisableReplaceStmt = DisableReplaceStmt;
5210 DisableReplaceStmt = false;
5211 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5212 DisableReplaceStmt = saveDisableReplaceStmt;
5213 CurrentBody = SaveCurrentBody;
5214 PropParentMap = 0;
5215 ImportedLocalExternalDecls.clear();
5216 // Now we snarf the rewritten text and stash it away for later use.
5217 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5218 RewrittenBlockExprs[BE] = Str;
5219
5220 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5221
5222 //blockTranscribed->dump();
5223 ReplaceStmt(S, blockTranscribed);
5224 return blockTranscribed;
5225 }
5226 // Handle specific things.
5227 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5228 return RewriteAtEncode(AtEncode);
5229
5230 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5231 return RewriteAtSelector(AtSelector);
5232
5233 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5234 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005235
5236 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5237 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005238
5239 if (ObjCNumericLiteral *NumericLitExpr = dyn_cast<ObjCNumericLiteral>(S))
5240 return RewriteObjCNumericLiteralExpr(NumericLitExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005241
5242 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5243 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005244
5245 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5246 dyn_cast<ObjCDictionaryLiteral>(S))
5247 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005248
5249 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5250#if 0
5251 // Before we rewrite it, put the original message expression in a comment.
5252 SourceLocation startLoc = MessExpr->getLocStart();
5253 SourceLocation endLoc = MessExpr->getLocEnd();
5254
5255 const char *startBuf = SM->getCharacterData(startLoc);
5256 const char *endBuf = SM->getCharacterData(endLoc);
5257
5258 std::string messString;
5259 messString += "// ";
5260 messString.append(startBuf, endBuf-startBuf+1);
5261 messString += "\n";
5262
5263 // FIXME: Missing definition of
5264 // InsertText(clang::SourceLocation, char const*, unsigned int).
5265 // InsertText(startLoc, messString.c_str(), messString.size());
5266 // Tried this, but it didn't work either...
5267 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5268#endif
5269 return RewriteMessageExpr(MessExpr);
5270 }
5271
5272 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5273 return RewriteObjCTryStmt(StmtTry);
5274
5275 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5276 return RewriteObjCSynchronizedStmt(StmtTry);
5277
5278 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5279 return RewriteObjCThrowStmt(StmtThrow);
5280
5281 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5282 return RewriteObjCProtocolExpr(ProtocolExp);
5283
5284 if (ObjCForCollectionStmt *StmtForCollection =
5285 dyn_cast<ObjCForCollectionStmt>(S))
5286 return RewriteObjCForCollectionStmt(StmtForCollection,
5287 OrigStmtRange.getEnd());
5288 if (BreakStmt *StmtBreakStmt =
5289 dyn_cast<BreakStmt>(S))
5290 return RewriteBreakStmt(StmtBreakStmt);
5291 if (ContinueStmt *StmtContinueStmt =
5292 dyn_cast<ContinueStmt>(S))
5293 return RewriteContinueStmt(StmtContinueStmt);
5294
5295 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5296 // and cast exprs.
5297 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5298 // FIXME: What we're doing here is modifying the type-specifier that
5299 // precedes the first Decl. In the future the DeclGroup should have
5300 // a separate type-specifier that we can rewrite.
5301 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5302 // the context of an ObjCForCollectionStmt. For example:
5303 // NSArray *someArray;
5304 // for (id <FooProtocol> index in someArray) ;
5305 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5306 // and it depends on the original text locations/positions.
5307 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5308 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5309
5310 // Blocks rewrite rules.
5311 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5312 DI != DE; ++DI) {
5313 Decl *SD = *DI;
5314 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5315 if (isTopLevelBlockPointerType(ND->getType()))
5316 RewriteBlockPointerDecl(ND);
5317 else if (ND->getType()->isFunctionPointerType())
5318 CheckFunctionPointerDecl(ND->getType(), ND);
5319 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5320 if (VD->hasAttr<BlocksAttr>()) {
5321 static unsigned uniqueByrefDeclCount = 0;
5322 assert(!BlockByRefDeclNo.count(ND) &&
5323 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5324 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5325 RewriteByRefVar(VD);
5326 }
5327 else
5328 RewriteTypeOfDecl(VD);
5329 }
5330 }
5331 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5332 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5333 RewriteBlockPointerDecl(TD);
5334 else if (TD->getUnderlyingType()->isFunctionPointerType())
5335 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5336 }
5337 }
5338 }
5339
5340 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5341 RewriteObjCQualifiedInterfaceTypes(CE);
5342
5343 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5344 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5345 assert(!Stmts.empty() && "Statement stack is empty");
5346 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5347 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5348 && "Statement stack mismatch");
5349 Stmts.pop_back();
5350 }
5351 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5353 ValueDecl *VD = DRE->getDecl();
5354 if (VD->hasAttr<BlocksAttr>())
5355 return RewriteBlockDeclRefExpr(DRE);
5356 if (HasLocalVariableExternalStorage(VD))
5357 return RewriteLocalVariableExternalStorage(DRE);
5358 }
5359
5360 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5361 if (CE->getCallee()->getType()->isBlockPointerType()) {
5362 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5363 ReplaceStmt(S, BlockCall);
5364 return BlockCall;
5365 }
5366 }
5367 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5368 RewriteCastExpr(CE);
5369 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005370 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5371 RewriteImplicitCastObjCExpr(ICE);
5372 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005373#if 0
5374 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5375 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5376 ICE->getSubExpr(),
5377 SourceLocation());
5378 // Get the new text.
5379 std::string SStr;
5380 llvm::raw_string_ostream Buf(SStr);
5381 Replacement->printPretty(Buf, *Context);
5382 const std::string &Str = Buf.str();
5383
5384 printf("CAST = %s\n", &Str[0]);
5385 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5386 delete S;
5387 return Replacement;
5388 }
5389#endif
5390 // Return this stmt unmodified.
5391 return S;
5392}
5393
5394void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5395 for (RecordDecl::field_iterator i = RD->field_begin(),
5396 e = RD->field_end(); i != e; ++i) {
5397 FieldDecl *FD = *i;
5398 if (isTopLevelBlockPointerType(FD->getType()))
5399 RewriteBlockPointerDecl(FD);
5400 if (FD->getType()->isObjCQualifiedIdType() ||
5401 FD->getType()->isObjCQualifiedInterfaceType())
5402 RewriteObjCQualifiedInterfaceTypes(FD);
5403 }
5404}
5405
5406/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5407/// main file of the input.
5408void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5409 switch (D->getKind()) {
5410 case Decl::Function: {
5411 FunctionDecl *FD = cast<FunctionDecl>(D);
5412 if (FD->isOverloadedOperator())
5413 return;
5414
5415 // Since function prototypes don't have ParmDecl's, we check the function
5416 // prototype. This enables us to rewrite function declarations and
5417 // definitions using the same code.
5418 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5419
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005420 if (!FD->isThisDeclarationADefinition())
5421 break;
5422
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005423 // FIXME: If this should support Obj-C++, support CXXTryStmt
5424 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5425 CurFunctionDef = FD;
5426 CurFunctionDeclToDeclareForBlock = FD;
5427 CurrentBody = Body;
5428 Body =
5429 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5430 FD->setBody(Body);
5431 CurrentBody = 0;
5432 if (PropParentMap) {
5433 delete PropParentMap;
5434 PropParentMap = 0;
5435 }
5436 // This synthesizes and inserts the block "impl" struct, invoke function,
5437 // and any copy/dispose helper functions.
5438 InsertBlockLiteralsWithinFunction(FD);
5439 CurFunctionDef = 0;
5440 CurFunctionDeclToDeclareForBlock = 0;
5441 }
5442 break;
5443 }
5444 case Decl::ObjCMethod: {
5445 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5446 if (CompoundStmt *Body = MD->getCompoundBody()) {
5447 CurMethodDef = MD;
5448 CurrentBody = Body;
5449 Body =
5450 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5451 MD->setBody(Body);
5452 CurrentBody = 0;
5453 if (PropParentMap) {
5454 delete PropParentMap;
5455 PropParentMap = 0;
5456 }
5457 InsertBlockLiteralsWithinMethod(MD);
5458 CurMethodDef = 0;
5459 }
5460 break;
5461 }
5462 case Decl::ObjCImplementation: {
5463 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5464 ClassImplementation.push_back(CI);
5465 break;
5466 }
5467 case Decl::ObjCCategoryImpl: {
5468 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5469 CategoryImplementation.push_back(CI);
5470 break;
5471 }
5472 case Decl::Var: {
5473 VarDecl *VD = cast<VarDecl>(D);
5474 RewriteObjCQualifiedInterfaceTypes(VD);
5475 if (isTopLevelBlockPointerType(VD->getType()))
5476 RewriteBlockPointerDecl(VD);
5477 else if (VD->getType()->isFunctionPointerType()) {
5478 CheckFunctionPointerDecl(VD->getType(), VD);
5479 if (VD->getInit()) {
5480 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5481 RewriteCastExpr(CE);
5482 }
5483 }
5484 } else if (VD->getType()->isRecordType()) {
5485 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5486 if (RD->isCompleteDefinition())
5487 RewriteRecordBody(RD);
5488 }
5489 if (VD->getInit()) {
5490 GlobalVarDecl = VD;
5491 CurrentBody = VD->getInit();
5492 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5493 CurrentBody = 0;
5494 if (PropParentMap) {
5495 delete PropParentMap;
5496 PropParentMap = 0;
5497 }
5498 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5499 GlobalVarDecl = 0;
5500
5501 // This is needed for blocks.
5502 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5503 RewriteCastExpr(CE);
5504 }
5505 }
5506 break;
5507 }
5508 case Decl::TypeAlias:
5509 case Decl::Typedef: {
5510 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5511 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5512 RewriteBlockPointerDecl(TD);
5513 else if (TD->getUnderlyingType()->isFunctionPointerType())
5514 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5515 }
5516 break;
5517 }
5518 case Decl::CXXRecord:
5519 case Decl::Record: {
5520 RecordDecl *RD = cast<RecordDecl>(D);
5521 if (RD->isCompleteDefinition())
5522 RewriteRecordBody(RD);
5523 break;
5524 }
5525 default:
5526 break;
5527 }
5528 // Nothing yet.
5529}
5530
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005531/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5532/// protocol reference symbols in the for of:
5533/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5534static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5535 ObjCProtocolDecl *PDecl,
5536 std::string &Result) {
5537 // Also output .objc_protorefs$B section and its meta-data.
5538 if (Context->getLangOpts().MicrosoftExt)
5539 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5540 Result += "struct _protocol_t *";
5541 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5542 Result += PDecl->getNameAsString();
5543 Result += " = &";
5544 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5545 Result += ";\n";
5546}
5547
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005548void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5549 if (Diags.hasErrorOccurred())
5550 return;
5551
5552 RewriteInclude();
5553
5554 // Here's a great place to add any extra declarations that may be needed.
5555 // Write out meta data for each @protocol(<expr>).
5556 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005557 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005558 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005559 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5560 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005561
5562 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005563 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5564 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5565 // Write struct declaration for the class matching its ivar declarations.
5566 // Note that for modern abi, this is postponed until the end of TU
5567 // because class extensions and the implementation might declare their own
5568 // private ivars.
5569 RewriteInterfaceDecl(CDecl);
5570 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005571
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005572 if (ClassImplementation.size() || CategoryImplementation.size())
5573 RewriteImplementations();
5574
5575 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5576 // we are done.
5577 if (const RewriteBuffer *RewriteBuf =
5578 Rewrite.getRewriteBufferFor(MainFileID)) {
5579 //printf("Changed:\n");
5580 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5581 } else {
5582 llvm::errs() << "No changes\n";
5583 }
5584
5585 if (ClassImplementation.size() || CategoryImplementation.size() ||
5586 ProtocolExprDecls.size()) {
5587 // Rewrite Objective-c meta data*
5588 std::string ResultStr;
5589 RewriteMetaDataIntoBuffer(ResultStr);
5590 // Emit metadata.
5591 *OutFile << ResultStr;
5592 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005593 // Emit ImageInfo;
5594 {
5595 std::string ResultStr;
5596 WriteImageInfo(ResultStr);
5597 *OutFile << ResultStr;
5598 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005599 OutFile->flush();
5600}
5601
5602void RewriteModernObjC::Initialize(ASTContext &context) {
5603 InitializeCommon(context);
5604
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005605 Preamble += "#ifndef __OBJC2__\n";
5606 Preamble += "#define __OBJC2__\n";
5607 Preamble += "#endif\n";
5608
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005609 // declaring objc_selector outside the parameter list removes a silly
5610 // scope related warning...
5611 if (IsHeader)
5612 Preamble = "#pragma once\n";
5613 Preamble += "struct objc_selector; struct objc_class;\n";
5614 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5615 Preamble += "struct objc_object *superClass; ";
5616 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005617 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005618 // These are currently generated.
5619 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005620 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005621 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5622 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005623 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5624 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005625 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005626 // These are generated but not necessary for functionality.
5627 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5628 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005629 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5630 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005631 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005632
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005633 // These need be generated for performance. Currently they are not,
5634 // using API calls instead.
5635 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5636 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5637 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5638
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005639 // Add a constructor for creating temporary objects.
5640 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5641 ": ";
5642 Preamble += "object(o), superClass(s) {} ";
5643 }
5644 Preamble += "};\n";
5645 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5646 Preamble += "typedef struct objc_object Protocol;\n";
5647 Preamble += "#define _REWRITER_typedef_Protocol\n";
5648 Preamble += "#endif\n";
5649 if (LangOpts.MicrosoftExt) {
5650 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5651 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005652 }
5653 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005654 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005655
5656 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5657 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5658 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5659 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5660 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5661
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005662 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5663 Preamble += "(const char *);\n";
5664 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5665 Preamble += "(struct objc_class *);\n";
5666 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5667 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005668 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005669 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005670 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5671 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005672 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5673 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5674 Preamble += "struct __objcFastEnumerationState {\n\t";
5675 Preamble += "unsigned long state;\n\t";
5676 Preamble += "void **itemsPtr;\n\t";
5677 Preamble += "unsigned long *mutationsPtr;\n\t";
5678 Preamble += "unsigned long extra[5];\n};\n";
5679 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5680 Preamble += "#define __FASTENUMERATIONSTATE\n";
5681 Preamble += "#endif\n";
5682 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5683 Preamble += "struct __NSConstantStringImpl {\n";
5684 Preamble += " int *isa;\n";
5685 Preamble += " int flags;\n";
5686 Preamble += " char *str;\n";
5687 Preamble += " long length;\n";
5688 Preamble += "};\n";
5689 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5690 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5691 Preamble += "#else\n";
5692 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5693 Preamble += "#endif\n";
5694 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5695 Preamble += "#endif\n";
5696 // Blocks preamble.
5697 Preamble += "#ifndef BLOCK_IMPL\n";
5698 Preamble += "#define BLOCK_IMPL\n";
5699 Preamble += "struct __block_impl {\n";
5700 Preamble += " void *isa;\n";
5701 Preamble += " int Flags;\n";
5702 Preamble += " int Reserved;\n";
5703 Preamble += " void *FuncPtr;\n";
5704 Preamble += "};\n";
5705 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5706 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5707 Preamble += "extern \"C\" __declspec(dllexport) "
5708 "void _Block_object_assign(void *, const void *, const int);\n";
5709 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5710 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5711 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5712 Preamble += "#else\n";
5713 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5714 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5715 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5716 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5717 Preamble += "#endif\n";
5718 Preamble += "#endif\n";
5719 if (LangOpts.MicrosoftExt) {
5720 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5721 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5722 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5723 Preamble += "#define __attribute__(X)\n";
5724 Preamble += "#endif\n";
5725 Preamble += "#define __weak\n";
5726 }
5727 else {
5728 Preamble += "#define __block\n";
5729 Preamble += "#define __weak\n";
5730 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005731
5732 // Declarations required for modern objective-c array and dictionary literals.
5733 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005734 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005735 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005736 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005737 Preamble += "\tva_list marker;\n";
5738 Preamble += "\tva_start(marker, count);\n";
5739 Preamble += "\tarr = new void *[count];\n";
5740 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5741 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5742 Preamble += "\tva_end( marker );\n";
5743 Preamble += " };\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005744 Preamble += " __NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005745 Preamble += "\tdelete[] arr;\n";
5746 Preamble += " }\n";
5747 Preamble += "};\n";
5748
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005749 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5750 // as this avoids warning in any 64bit/32bit compilation model.
5751 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5752}
5753
5754/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5755/// ivar offset.
5756void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5757 std::string &Result) {
5758 if (ivar->isBitField()) {
5759 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5760 // place all bitfields at offset 0.
5761 Result += "0";
5762 } else {
5763 Result += "__OFFSETOFIVAR__(struct ";
5764 Result += ivar->getContainingInterface()->getNameAsString();
5765 if (LangOpts.MicrosoftExt)
5766 Result += "_IMPL";
5767 Result += ", ";
5768 Result += ivar->getNameAsString();
5769 Result += ")";
5770 }
5771}
5772
5773/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5774/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005775/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005776/// char *attributes;
5777/// }
5778
5779/// struct _prop_list_t {
5780/// uint32_t entsize; // sizeof(struct _prop_t)
5781/// uint32_t count_of_properties;
5782/// struct _prop_t prop_list[count_of_properties];
5783/// }
5784
5785/// struct _protocol_t;
5786
5787/// struct _protocol_list_t {
5788/// long protocol_count; // Note, this is 32/64 bit
5789/// struct _protocol_t * protocol_list[protocol_count];
5790/// }
5791
5792/// struct _objc_method {
5793/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005794/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005795/// char *_imp;
5796/// }
5797
5798/// struct _method_list_t {
5799/// uint32_t entsize; // sizeof(struct _objc_method)
5800/// uint32_t method_count;
5801/// struct _objc_method method_list[method_count];
5802/// }
5803
5804/// struct _protocol_t {
5805/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005806/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005807/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005808/// const struct method_list_t *instance_methods;
5809/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005810/// const struct method_list_t *optionalInstanceMethods;
5811/// const struct method_list_t *optionalClassMethods;
5812/// const struct _prop_list_t * properties;
5813/// const uint32_t size; // sizeof(struct _protocol_t)
5814/// const uint32_t flags; // = 0
5815/// const char ** extendedMethodTypes;
5816/// }
5817
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005818/// struct _ivar_t {
5819/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005820/// const char *name;
5821/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005822/// uint32_t alignment;
5823/// uint32_t size;
5824/// }
5825
5826/// struct _ivar_list_t {
5827/// uint32 entsize; // sizeof(struct _ivar_t)
5828/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005829/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005830/// }
5831
5832/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005833/// uint32_t flags;
5834/// uint32_t instanceStart;
5835/// uint32_t instanceSize;
5836/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005837/// const uint8_t *ivarLayout;
5838/// const char *name;
5839/// const struct _method_list_t *baseMethods;
5840/// const struct _protocol_list_t *baseProtocols;
5841/// const struct _ivar_list_t *ivars;
5842/// const uint8_t *weakIvarLayout;
5843/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005844/// }
5845
5846/// struct _class_t {
5847/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005848/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005849/// void *cache;
5850/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005851/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005852/// }
5853
5854/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005855/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005856/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005857/// const struct _method_list_t *instance_methods;
5858/// const struct _method_list_t *class_methods;
5859/// const struct _protocol_list_t *protocols;
5860/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005861/// }
5862
5863/// MessageRefTy - LLVM for:
5864/// struct _message_ref_t {
5865/// IMP messenger;
5866/// SEL name;
5867/// };
5868
5869/// SuperMessageRefTy - LLVM for:
5870/// struct _super_message_ref_t {
5871/// SUPER_IMP messenger;
5872/// SEL name;
5873/// };
5874
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005875static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005876 static bool meta_data_declared = false;
5877 if (meta_data_declared)
5878 return;
5879
5880 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005881 Result += "\tconst char *name;\n";
5882 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005883 Result += "};\n";
5884
5885 Result += "\nstruct _protocol_t;\n";
5886
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005887 Result += "\nstruct _objc_method {\n";
5888 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005889 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005890 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005891 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005892
5893 Result += "\nstruct _protocol_t {\n";
5894 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005895 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005896 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005897 Result += "\tconst struct method_list_t *instance_methods;\n";
5898 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005899 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5900 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5901 Result += "\tconst struct _prop_list_t * properties;\n";
5902 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5903 Result += "\tconst unsigned int flags; // = 0\n";
5904 Result += "\tconst char ** extendedMethodTypes;\n";
5905 Result += "};\n";
5906
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005907 Result += "\nstruct _ivar_t {\n";
5908 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005909 Result += "\tconst char *name;\n";
5910 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005911 Result += "\tunsigned int alignment;\n";
5912 Result += "\tunsigned int size;\n";
5913 Result += "};\n";
5914
5915 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005916 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005917 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005918 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005919 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5920 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005921 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005922 Result += "\tconst unsigned char *ivarLayout;\n";
5923 Result += "\tconst char *name;\n";
5924 Result += "\tconst struct _method_list_t *baseMethods;\n";
5925 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5926 Result += "\tconst struct _ivar_list_t *ivars;\n";
5927 Result += "\tconst unsigned char *weakIvarLayout;\n";
5928 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005929 Result += "};\n";
5930
5931 Result += "\nstruct _class_t {\n";
5932 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005933 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005934 Result += "\tvoid *cache;\n";
5935 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005936 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005937 Result += "};\n";
5938
5939 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005940 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005941 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005942 Result += "\tconst struct _method_list_t *instance_methods;\n";
5943 Result += "\tconst struct _method_list_t *class_methods;\n";
5944 Result += "\tconst struct _protocol_list_t *protocols;\n";
5945 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005946 Result += "};\n";
5947
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005948 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005949 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005950 meta_data_declared = true;
5951}
5952
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005953static void Write_protocol_list_t_TypeDecl(std::string &Result,
5954 long super_protocol_count) {
5955 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5956 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5957 Result += "\tstruct _protocol_t *super_protocols[";
5958 Result += utostr(super_protocol_count); Result += "];\n";
5959 Result += "}";
5960}
5961
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005962static void Write_method_list_t_TypeDecl(std::string &Result,
5963 unsigned int method_count) {
5964 Result += "struct /*_method_list_t*/"; Result += " {\n";
5965 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5966 Result += "\tunsigned int method_count;\n";
5967 Result += "\tstruct _objc_method method_list[";
5968 Result += utostr(method_count); Result += "];\n";
5969 Result += "}";
5970}
5971
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005972static void Write__prop_list_t_TypeDecl(std::string &Result,
5973 unsigned int property_count) {
5974 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5975 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5976 Result += "\tunsigned int count_of_properties;\n";
5977 Result += "\tstruct _prop_t prop_list[";
5978 Result += utostr(property_count); Result += "];\n";
5979 Result += "}";
5980}
5981
Fariborz Jahanianae932952012-02-10 20:47:10 +00005982static void Write__ivar_list_t_TypeDecl(std::string &Result,
5983 unsigned int ivar_count) {
5984 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5985 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5986 Result += "\tunsigned int count;\n";
5987 Result += "\tstruct _ivar_t ivar_list[";
5988 Result += utostr(ivar_count); Result += "];\n";
5989 Result += "}";
5990}
5991
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005992static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5993 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5994 StringRef VarName,
5995 StringRef ProtocolName) {
5996 if (SuperProtocols.size() > 0) {
5997 Result += "\nstatic ";
5998 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5999 Result += " "; Result += VarName;
6000 Result += ProtocolName;
6001 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6002 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6003 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6004 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6005 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6006 Result += SuperPD->getNameAsString();
6007 if (i == e-1)
6008 Result += "\n};\n";
6009 else
6010 Result += ",\n";
6011 }
6012 }
6013}
6014
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006015static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6016 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006017 ArrayRef<ObjCMethodDecl *> Methods,
6018 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006019 StringRef TopLevelDeclName,
6020 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006021 if (Methods.size() > 0) {
6022 Result += "\nstatic ";
6023 Write_method_list_t_TypeDecl(Result, Methods.size());
6024 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006025 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006026 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6027 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6028 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6029 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6030 ObjCMethodDecl *MD = Methods[i];
6031 if (i == 0)
6032 Result += "\t{{(struct objc_selector *)\"";
6033 else
6034 Result += "\t{(struct objc_selector *)\"";
6035 Result += (MD)->getSelector().getAsString(); Result += "\"";
6036 Result += ", ";
6037 std::string MethodTypeString;
6038 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6039 Result += "\""; Result += MethodTypeString; Result += "\"";
6040 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006041 if (!MethodImpl)
6042 Result += "0";
6043 else {
6044 Result += "(void *)";
6045 Result += RewriteObj.MethodInternalNames[MD];
6046 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006047 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006048 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006049 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006050 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006051 }
6052 Result += "};\n";
6053 }
6054}
6055
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006056static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006057 ASTContext *Context, std::string &Result,
6058 ArrayRef<ObjCPropertyDecl *> Properties,
6059 const Decl *Container,
6060 StringRef VarName,
6061 StringRef ProtocolName) {
6062 if (Properties.size() > 0) {
6063 Result += "\nstatic ";
6064 Write__prop_list_t_TypeDecl(Result, Properties.size());
6065 Result += " "; Result += VarName;
6066 Result += ProtocolName;
6067 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6068 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6069 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6070 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6071 ObjCPropertyDecl *PropDecl = Properties[i];
6072 if (i == 0)
6073 Result += "\t{{\"";
6074 else
6075 Result += "\t{\"";
6076 Result += PropDecl->getName(); Result += "\",";
6077 std::string PropertyTypeString, QuotePropertyTypeString;
6078 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6079 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6080 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6081 if (i == e-1)
6082 Result += "}}\n";
6083 else
6084 Result += "},\n";
6085 }
6086 Result += "};\n";
6087 }
6088}
6089
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006090// Metadata flags
6091enum MetaDataDlags {
6092 CLS = 0x0,
6093 CLS_META = 0x1,
6094 CLS_ROOT = 0x2,
6095 OBJC2_CLS_HIDDEN = 0x10,
6096 CLS_EXCEPTION = 0x20,
6097
6098 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6099 CLS_HAS_IVAR_RELEASER = 0x40,
6100 /// class was compiled with -fobjc-arr
6101 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6102};
6103
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006104static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6105 unsigned int flags,
6106 const std::string &InstanceStart,
6107 const std::string &InstanceSize,
6108 ArrayRef<ObjCMethodDecl *>baseMethods,
6109 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6110 ArrayRef<ObjCIvarDecl *>ivars,
6111 ArrayRef<ObjCPropertyDecl *>Properties,
6112 StringRef VarName,
6113 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006114 Result += "\nstatic struct _class_ro_t ";
6115 Result += VarName; Result += ClassName;
6116 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6117 Result += "\t";
6118 Result += llvm::utostr(flags); Result += ", ";
6119 Result += InstanceStart; Result += ", ";
6120 Result += InstanceSize; Result += ", \n";
6121 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006122 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6123 if (Triple.getArch() == llvm::Triple::x86_64)
6124 // uint32_t const reserved; // only when building for 64bit targets
6125 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006126 // const uint8_t * const ivarLayout;
6127 Result += "0, \n\t";
6128 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006129 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006130 if (baseMethods.size() > 0) {
6131 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006132 if (metaclass)
6133 Result += "_OBJC_$_CLASS_METHODS_";
6134 else
6135 Result += "_OBJC_$_INSTANCE_METHODS_";
6136 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006137 Result += ",\n\t";
6138 }
6139 else
6140 Result += "0, \n\t";
6141
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006142 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006143 Result += "(const struct _objc_protocol_list *)&";
6144 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6145 Result += ",\n\t";
6146 }
6147 else
6148 Result += "0, \n\t";
6149
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006150 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006151 Result += "(const struct _ivar_list_t *)&";
6152 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6153 Result += ",\n\t";
6154 }
6155 else
6156 Result += "0, \n\t";
6157
6158 // weakIvarLayout
6159 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006160 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006161 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006162 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006163 Result += ",\n";
6164 }
6165 else
6166 Result += "0, \n";
6167
6168 Result += "};\n";
6169}
6170
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006171static void Write_class_t(ASTContext *Context, std::string &Result,
6172 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006173 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6174 bool rootClass = (!CDecl->getSuperClass());
6175 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006176
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006177 if (!rootClass) {
6178 // Find the Root class
6179 RootClass = CDecl->getSuperClass();
6180 while (RootClass->getSuperClass()) {
6181 RootClass = RootClass->getSuperClass();
6182 }
6183 }
6184
6185 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006186 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006187 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006188 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006189 if (CDecl->getImplementation())
6190 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006191 else
6192 Result += "__declspec(dllimport) ";
6193
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006194 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006195 Result += CDecl->getNameAsString();
6196 Result += ";\n";
6197 }
6198 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006199 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006200 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006201 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006202 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006203 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006204 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 Jahaniance0d8972012-03-10 18:25:06 +00006209 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006210 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006211 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006212
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006213 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006214 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006215 if (RootClass->getImplementation())
6216 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006217 else
6218 Result += "__declspec(dllimport) ";
6219
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006220 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006221 Result += VarName;
6222 Result += RootClass->getNameAsString();
6223 Result += ";\n";
6224 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006225 }
6226
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006227 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6228 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006229 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6230 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006231 if (metaclass) {
6232 if (!rootClass) {
6233 Result += "0, // &"; Result += VarName;
6234 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006235 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006236 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006237 Result += CDecl->getSuperClass()->getNameAsString();
6238 Result += ",\n\t";
6239 }
6240 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006241 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006242 Result += CDecl->getNameAsString();
6243 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006244 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006245 Result += ",\n\t";
6246 }
6247 }
6248 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006249 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006250 Result += CDecl->getNameAsString();
6251 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006252 if (!rootClass) {
6253 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006254 Result += CDecl->getSuperClass()->getNameAsString();
6255 Result += ",\n\t";
6256 }
6257 else
6258 Result += "0,\n\t";
6259 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006260 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6261 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6262 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006263 Result += "&_OBJC_METACLASS_RO_$_";
6264 else
6265 Result += "&_OBJC_CLASS_RO_$_";
6266 Result += CDecl->getNameAsString();
6267 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006268
6269 // Add static function to initialize some of the meta-data fields.
6270 // avoid doing it twice.
6271 if (metaclass)
6272 return;
6273
6274 const ObjCInterfaceDecl *SuperClass =
6275 rootClass ? CDecl : CDecl->getSuperClass();
6276
6277 Result += "static void OBJC_CLASS_SETUP_$_";
6278 Result += CDecl->getNameAsString();
6279 Result += "(void ) {\n";
6280 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6281 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006282 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006283
6284 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006285 Result += ".superclass = ";
6286 if (rootClass)
6287 Result += "&OBJC_CLASS_$_";
6288 else
6289 Result += "&OBJC_METACLASS_$_";
6290
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006291 Result += SuperClass->getNameAsString(); Result += ";\n";
6292
6293 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6294 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6295
6296 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6297 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6298 Result += CDecl->getNameAsString(); Result += ";\n";
6299
6300 if (!rootClass) {
6301 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6302 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6303 Result += SuperClass->getNameAsString(); Result += ";\n";
6304 }
6305
6306 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6307 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6308 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006309}
6310
Fariborz Jahanian61186122012-02-17 18:40:41 +00006311static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6312 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006313 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006314 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006315 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6316 ArrayRef<ObjCMethodDecl *> ClassMethods,
6317 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6318 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006319 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006320 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006321 // must declare an extern class object in case this class is not implemented
6322 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006323 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006324 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006325 if (ClassDecl->getImplementation())
6326 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006327 else
6328 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006329
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006330 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006331 Result += "OBJC_CLASS_$_"; Result += ClassName;
6332 Result += ";\n";
6333
Fariborz Jahanian61186122012-02-17 18:40:41 +00006334 Result += "\nstatic struct _category_t ";
6335 Result += "_OBJC_$_CATEGORY_";
6336 Result += ClassName; Result += "_$_"; Result += CatName;
6337 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6338 Result += "{\n";
6339 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006340 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006341 Result += ",\n";
6342 if (InstanceMethods.size() > 0) {
6343 Result += "\t(const struct _method_list_t *)&";
6344 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6345 Result += ClassName; Result += "_$_"; Result += CatName;
6346 Result += ",\n";
6347 }
6348 else
6349 Result += "\t0,\n";
6350
6351 if (ClassMethods.size() > 0) {
6352 Result += "\t(const struct _method_list_t *)&";
6353 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6354 Result += ClassName; Result += "_$_"; Result += CatName;
6355 Result += ",\n";
6356 }
6357 else
6358 Result += "\t0,\n";
6359
6360 if (RefedProtocols.size() > 0) {
6361 Result += "\t(const struct _protocol_list_t *)&";
6362 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6363 Result += ClassName; Result += "_$_"; Result += CatName;
6364 Result += ",\n";
6365 }
6366 else
6367 Result += "\t0,\n";
6368
6369 if (ClassProperties.size() > 0) {
6370 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6371 Result += ClassName; Result += "_$_"; Result += CatName;
6372 Result += ",\n";
6373 }
6374 else
6375 Result += "\t0,\n";
6376
6377 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006378
6379 // Add static function to initialize the class pointer in the category structure.
6380 Result += "static void OBJC_CATEGORY_SETUP_$_";
6381 Result += ClassDecl->getNameAsString();
6382 Result += "_$_";
6383 Result += CatName;
6384 Result += "(void ) {\n";
6385 Result += "\t_OBJC_$_CATEGORY_";
6386 Result += ClassDecl->getNameAsString();
6387 Result += "_$_";
6388 Result += CatName;
6389 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6390 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006391}
6392
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006393static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6394 ASTContext *Context, std::string &Result,
6395 ArrayRef<ObjCMethodDecl *> Methods,
6396 StringRef VarName,
6397 StringRef ProtocolName) {
6398 if (Methods.size() == 0)
6399 return;
6400
6401 Result += "\nstatic const char *";
6402 Result += VarName; Result += ProtocolName;
6403 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6404 Result += "{\n";
6405 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6406 ObjCMethodDecl *MD = Methods[i];
6407 std::string MethodTypeString, QuoteMethodTypeString;
6408 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6409 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6410 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6411 if (i == e-1)
6412 Result += "\n};\n";
6413 else {
6414 Result += ",\n";
6415 }
6416 }
6417}
6418
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006419static void Write_IvarOffsetVar(ASTContext *Context,
6420 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006421 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006422 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006423 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6424 // this is what happens:
6425 /**
6426 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6427 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6428 Class->getVisibility() == HiddenVisibility)
6429 Visibility shoud be: HiddenVisibility;
6430 else
6431 Visibility shoud be: DefaultVisibility;
6432 */
6433
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006434 Result += "\n";
6435 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6436 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006437 if (Context->getLangOpts().MicrosoftExt)
6438 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6439
6440 if (!Context->getLangOpts().MicrosoftExt ||
6441 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006442 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006443 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006444 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006445 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006446 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006447 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6448 Result += " = ";
6449 if (IvarDecl->isBitField()) {
6450 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6451 // place all bitfields at offset 0.
6452 Result += "0;\n";
6453 }
6454 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006455 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006456 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006457 Result += "_IMPL, ";
6458 Result += IvarDecl->getName(); Result += ");\n";
6459 }
6460 }
6461}
6462
Fariborz Jahanianae932952012-02-10 20:47:10 +00006463static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6464 ASTContext *Context, std::string &Result,
6465 ArrayRef<ObjCIvarDecl *> Ivars,
6466 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006467 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006468 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006469 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006470
Fariborz Jahanianae932952012-02-10 20:47:10 +00006471 Result += "\nstatic ";
6472 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6473 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006474 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006475 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6476 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6477 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6478 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6479 ObjCIvarDecl *IvarDecl = Ivars[i];
6480 if (i == 0)
6481 Result += "\t{{";
6482 else
6483 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006484 Result += "(unsigned long int *)&";
6485 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006486 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006487
6488 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6489 std::string IvarTypeString, QuoteIvarTypeString;
6490 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6491 IvarDecl);
6492 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6493 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6494
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006495 // FIXME. this alignment represents the host alignment and need be changed to
6496 // represent the target alignment.
6497 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6498 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006499 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006500 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6501 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006502 if (i == e-1)
6503 Result += "}}\n";
6504 else
6505 Result += "},\n";
6506 }
6507 Result += "};\n";
6508 }
6509}
6510
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006511/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006512void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6513 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006514
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006515 // Do not synthesize the protocol more than once.
6516 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6517 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006518 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006519
6520 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6521 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006522 // Must write out all protocol definitions in current qualifier list,
6523 // and in their nested qualifiers before writing out current definition.
6524 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6525 E = PDecl->protocol_end(); I != E; ++I)
6526 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006527
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006528 // Construct method lists.
6529 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6530 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6531 for (ObjCProtocolDecl::instmeth_iterator
6532 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6533 I != E; ++I) {
6534 ObjCMethodDecl *MD = *I;
6535 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6536 OptInstanceMethods.push_back(MD);
6537 } else {
6538 InstanceMethods.push_back(MD);
6539 }
6540 }
6541
6542 for (ObjCProtocolDecl::classmeth_iterator
6543 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6544 I != E; ++I) {
6545 ObjCMethodDecl *MD = *I;
6546 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6547 OptClassMethods.push_back(MD);
6548 } else {
6549 ClassMethods.push_back(MD);
6550 }
6551 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006552 std::vector<ObjCMethodDecl *> AllMethods;
6553 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6554 AllMethods.push_back(InstanceMethods[i]);
6555 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6556 AllMethods.push_back(ClassMethods[i]);
6557 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6558 AllMethods.push_back(OptInstanceMethods[i]);
6559 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6560 AllMethods.push_back(OptClassMethods[i]);
6561
6562 Write__extendedMethodTypes_initializer(*this, Context, Result,
6563 AllMethods,
6564 "_OBJC_PROTOCOL_METHOD_TYPES_",
6565 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006566 // Protocol's super protocol list
6567 std::vector<ObjCProtocolDecl *> SuperProtocols;
6568 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6569 E = PDecl->protocol_end(); I != E; ++I)
6570 SuperProtocols.push_back(*I);
6571
6572 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6573 "_OBJC_PROTOCOL_REFS_",
6574 PDecl->getNameAsString());
6575
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006576 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006577 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006578 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006579
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006580 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006581 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006582 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006583
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006584 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006585 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006586 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006587
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006588 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006589 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006590 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006591
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006592 // Protocol's property metadata.
6593 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6594 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6595 E = PDecl->prop_end(); I != E; ++I)
6596 ProtocolProperties.push_back(*I);
6597
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006598 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006599 /* Container */0,
6600 "_OBJC_PROTOCOL_PROPERTIES_",
6601 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006602
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006603 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006604 Result += "\n";
6605 if (LangOpts.MicrosoftExt)
6606 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006607 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006608 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006609 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6610 Result += "\t0,\n"; // id is; is null
6611 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006612 if (SuperProtocols.size() > 0) {
6613 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6614 Result += PDecl->getNameAsString(); Result += ",\n";
6615 }
6616 else
6617 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006618 if (InstanceMethods.size() > 0) {
6619 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6620 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006621 }
6622 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006623 Result += "\t0,\n";
6624
6625 if (ClassMethods.size() > 0) {
6626 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6627 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006628 }
6629 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006630 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006631
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006632 if (OptInstanceMethods.size() > 0) {
6633 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6634 Result += PDecl->getNameAsString(); Result += ",\n";
6635 }
6636 else
6637 Result += "\t0,\n";
6638
6639 if (OptClassMethods.size() > 0) {
6640 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6641 Result += PDecl->getNameAsString(); Result += ",\n";
6642 }
6643 else
6644 Result += "\t0,\n";
6645
6646 if (ProtocolProperties.size() > 0) {
6647 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6648 Result += PDecl->getNameAsString(); Result += ",\n";
6649 }
6650 else
6651 Result += "\t0,\n";
6652
6653 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6654 Result += "\t0,\n";
6655
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006656 if (AllMethods.size() > 0) {
6657 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6658 Result += PDecl->getNameAsString();
6659 Result += "\n};\n";
6660 }
6661 else
6662 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006663
6664 // Use this protocol meta-data to build protocol list table in section
6665 // .objc_protolist$B
6666 // Unspecified visibility means 'private extern'.
6667 if (LangOpts.MicrosoftExt)
6668 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6669 Result += "struct _protocol_t *";
6670 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6671 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6672 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006673
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006674 // Mark this protocol as having been generated.
6675 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6676 llvm_unreachable("protocol already synthesized");
6677
6678}
6679
6680void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6681 const ObjCList<ObjCProtocolDecl> &Protocols,
6682 StringRef prefix, StringRef ClassName,
6683 std::string &Result) {
6684 if (Protocols.empty()) return;
6685
6686 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006687 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006688
6689 // Output the top lovel protocol meta-data for the class.
6690 /* struct _objc_protocol_list {
6691 struct _objc_protocol_list *next;
6692 int protocol_count;
6693 struct _objc_protocol *class_protocols[];
6694 }
6695 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006696 Result += "\n";
6697 if (LangOpts.MicrosoftExt)
6698 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6699 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006700 Result += "\tstruct _objc_protocol_list *next;\n";
6701 Result += "\tint protocol_count;\n";
6702 Result += "\tstruct _objc_protocol *class_protocols[";
6703 Result += utostr(Protocols.size());
6704 Result += "];\n} _OBJC_";
6705 Result += prefix;
6706 Result += "_PROTOCOLS_";
6707 Result += ClassName;
6708 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6709 "{\n\t0, ";
6710 Result += utostr(Protocols.size());
6711 Result += "\n";
6712
6713 Result += "\t,{&_OBJC_PROTOCOL_";
6714 Result += Protocols[0]->getNameAsString();
6715 Result += " \n";
6716
6717 for (unsigned i = 1; i != Protocols.size(); i++) {
6718 Result += "\t ,&_OBJC_PROTOCOL_";
6719 Result += Protocols[i]->getNameAsString();
6720 Result += "\n";
6721 }
6722 Result += "\t }\n};\n";
6723}
6724
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006725/// hasObjCExceptionAttribute - Return true if this class or any super
6726/// class has the __objc_exception__ attribute.
6727/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6728static bool hasObjCExceptionAttribute(ASTContext &Context,
6729 const ObjCInterfaceDecl *OID) {
6730 if (OID->hasAttr<ObjCExceptionAttr>())
6731 return true;
6732 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6733 return hasObjCExceptionAttribute(Context, Super);
6734 return false;
6735}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006736
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006737void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6738 std::string &Result) {
6739 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6740
6741 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006742 if (CDecl->isImplicitInterfaceDecl())
6743 assert(false &&
6744 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006745
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006746 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006747 SmallVector<ObjCIvarDecl *, 8> IVars;
6748
6749 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6750 IVD; IVD = IVD->getNextIvar()) {
6751 // Ignore unnamed bit-fields.
6752 if (!IVD->getDeclName())
6753 continue;
6754 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006755 }
6756
Fariborz Jahanianae932952012-02-10 20:47:10 +00006757 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006758 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006759 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006760
6761 // Build _objc_method_list for class's instance methods if needed
6762 SmallVector<ObjCMethodDecl *, 32>
6763 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6764
6765 // If any of our property implementations have associated getters or
6766 // setters, produce metadata for them as well.
6767 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6768 PropEnd = IDecl->propimpl_end();
6769 Prop != PropEnd; ++Prop) {
6770 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6771 continue;
6772 if (!(*Prop)->getPropertyIvarDecl())
6773 continue;
6774 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6775 if (!PD)
6776 continue;
6777 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6778 if (!Getter->isDefined())
6779 InstanceMethods.push_back(Getter);
6780 if (PD->isReadOnly())
6781 continue;
6782 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6783 if (!Setter->isDefined())
6784 InstanceMethods.push_back(Setter);
6785 }
6786
6787 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6788 "_OBJC_$_INSTANCE_METHODS_",
6789 IDecl->getNameAsString(), true);
6790
6791 SmallVector<ObjCMethodDecl *, 32>
6792 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6793
6794 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6795 "_OBJC_$_CLASS_METHODS_",
6796 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006797
6798 // Protocols referenced in class declaration?
6799 // Protocol's super protocol list
6800 std::vector<ObjCProtocolDecl *> RefedProtocols;
6801 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6802 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6803 E = Protocols.end();
6804 I != E; ++I) {
6805 RefedProtocols.push_back(*I);
6806 // Must write out all protocol definitions in current qualifier list,
6807 // and in their nested qualifiers before writing out current definition.
6808 RewriteObjCProtocolMetaData(*I, Result);
6809 }
6810
6811 Write_protocol_list_initializer(Context, Result,
6812 RefedProtocols,
6813 "_OBJC_CLASS_PROTOCOLS_$_",
6814 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006815
6816 // Protocol's property metadata.
6817 std::vector<ObjCPropertyDecl *> ClassProperties;
6818 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6819 E = CDecl->prop_end(); I != E; ++I)
6820 ClassProperties.push_back(*I);
6821
6822 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006823 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006824 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006825 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006826
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006827
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006828 // Data for initializing _class_ro_t metaclass meta-data
6829 uint32_t flags = CLS_META;
6830 std::string InstanceSize;
6831 std::string InstanceStart;
6832
6833
6834 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6835 if (classIsHidden)
6836 flags |= OBJC2_CLS_HIDDEN;
6837
6838 if (!CDecl->getSuperClass())
6839 // class is root
6840 flags |= CLS_ROOT;
6841 InstanceSize = "sizeof(struct _class_t)";
6842 InstanceStart = InstanceSize;
6843 Write__class_ro_t_initializer(Context, Result, flags,
6844 InstanceStart, InstanceSize,
6845 ClassMethods,
6846 0,
6847 0,
6848 0,
6849 "_OBJC_METACLASS_RO_$_",
6850 CDecl->getNameAsString());
6851
6852
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006853 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006854 flags = CLS;
6855 if (classIsHidden)
6856 flags |= OBJC2_CLS_HIDDEN;
6857
6858 if (hasObjCExceptionAttribute(*Context, CDecl))
6859 flags |= CLS_EXCEPTION;
6860
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006861 if (!CDecl->getSuperClass())
6862 // class is root
6863 flags |= CLS_ROOT;
6864
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006865 InstanceSize.clear();
6866 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006867 if (!ObjCSynthesizedStructs.count(CDecl)) {
6868 InstanceSize = "0";
6869 InstanceStart = "0";
6870 }
6871 else {
6872 InstanceSize = "sizeof(struct ";
6873 InstanceSize += CDecl->getNameAsString();
6874 InstanceSize += "_IMPL)";
6875
6876 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6877 if (IVD) {
6878 InstanceStart += "__OFFSETOFIVAR__(struct ";
6879 InstanceStart += CDecl->getNameAsString();
6880 InstanceStart += "_IMPL, ";
6881 InstanceStart += IVD->getNameAsString();
6882 InstanceStart += ")";
6883 }
6884 else
6885 InstanceStart = InstanceSize;
6886 }
6887 Write__class_ro_t_initializer(Context, Result, flags,
6888 InstanceStart, InstanceSize,
6889 InstanceMethods,
6890 RefedProtocols,
6891 IVars,
6892 ClassProperties,
6893 "_OBJC_CLASS_RO_$_",
6894 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006895
6896 Write_class_t(Context, Result,
6897 "OBJC_METACLASS_$_",
6898 CDecl, /*metaclass*/true);
6899
6900 Write_class_t(Context, Result,
6901 "OBJC_CLASS_$_",
6902 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006903
6904 if (ImplementationIsNonLazy(IDecl))
6905 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006906
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006907}
6908
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006909void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6910 int ClsDefCount = ClassImplementation.size();
6911 if (!ClsDefCount)
6912 return;
6913 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6914 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6915 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6916 for (int i = 0; i < ClsDefCount; i++) {
6917 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6918 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6919 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6920 Result += CDecl->getName(); Result += ",\n";
6921 }
6922 Result += "};\n";
6923}
6924
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006925void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6926 int ClsDefCount = ClassImplementation.size();
6927 int CatDefCount = CategoryImplementation.size();
6928
6929 // For each implemented class, write out all its meta data.
6930 for (int i = 0; i < ClsDefCount; i++)
6931 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6932
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006933 RewriteClassSetupInitHook(Result);
6934
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006935 // For each implemented category, write out all its meta data.
6936 for (int i = 0; i < CatDefCount; i++)
6937 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6938
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006939 RewriteCategorySetupInitHook(Result);
6940
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006941 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006942 if (LangOpts.MicrosoftExt)
6943 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006944 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6945 Result += llvm::utostr(ClsDefCount); Result += "]";
6946 Result +=
6947 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6948 "regular,no_dead_strip\")))= {\n";
6949 for (int i = 0; i < ClsDefCount; i++) {
6950 Result += "\t&OBJC_CLASS_$_";
6951 Result += ClassImplementation[i]->getNameAsString();
6952 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006953 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006954 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006955
6956 if (!DefinedNonLazyClasses.empty()) {
6957 if (LangOpts.MicrosoftExt)
6958 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6959 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6960 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6961 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6962 Result += ",\n";
6963 }
6964 Result += "};\n";
6965 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006966 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006967
6968 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006969 if (LangOpts.MicrosoftExt)
6970 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006971 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6972 Result += llvm::utostr(CatDefCount); Result += "]";
6973 Result +=
6974 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6975 "regular,no_dead_strip\")))= {\n";
6976 for (int i = 0; i < CatDefCount; i++) {
6977 Result += "\t&_OBJC_$_CATEGORY_";
6978 Result +=
6979 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6980 Result += "_$_";
6981 Result += CategoryImplementation[i]->getNameAsString();
6982 Result += ",\n";
6983 }
6984 Result += "};\n";
6985 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006986
6987 if (!DefinedNonLazyCategories.empty()) {
6988 if (LangOpts.MicrosoftExt)
6989 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6990 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6991 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6992 Result += "\t&_OBJC_$_CATEGORY_";
6993 Result +=
6994 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6995 Result += "_$_";
6996 Result += DefinedNonLazyCategories[i]->getNameAsString();
6997 Result += ",\n";
6998 }
6999 Result += "};\n";
7000 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007001}
7002
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007003void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7004 if (LangOpts.MicrosoftExt)
7005 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7006
7007 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7008 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007009 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007010}
7011
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007012/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7013/// implementation.
7014void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7015 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007016 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007017 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7018 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007019 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007020 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7021 CDecl = CDecl->getNextClassCategory())
7022 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7023 break;
7024
7025 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007026 FullCategoryName += "_$_";
7027 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007028
7029 // Build _objc_method_list for class's instance methods if needed
7030 SmallVector<ObjCMethodDecl *, 32>
7031 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7032
7033 // If any of our property implementations have associated getters or
7034 // setters, produce metadata for them as well.
7035 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7036 PropEnd = IDecl->propimpl_end();
7037 Prop != PropEnd; ++Prop) {
7038 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7039 continue;
7040 if (!(*Prop)->getPropertyIvarDecl())
7041 continue;
7042 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
7043 if (!PD)
7044 continue;
7045 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7046 InstanceMethods.push_back(Getter);
7047 if (PD->isReadOnly())
7048 continue;
7049 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7050 InstanceMethods.push_back(Setter);
7051 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007052
Fariborz Jahanian61186122012-02-17 18:40:41 +00007053 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7054 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7055 FullCategoryName, true);
7056
7057 SmallVector<ObjCMethodDecl *, 32>
7058 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7059
7060 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7061 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7062 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007063
7064 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007065 // Protocol's super protocol list
7066 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007067 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7068 E = CDecl->protocol_end();
7069
7070 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007071 RefedProtocols.push_back(*I);
7072 // Must write out all protocol definitions in current qualifier list,
7073 // and in their nested qualifiers before writing out current definition.
7074 RewriteObjCProtocolMetaData(*I, Result);
7075 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007076
Fariborz Jahanian61186122012-02-17 18:40:41 +00007077 Write_protocol_list_initializer(Context, Result,
7078 RefedProtocols,
7079 "_OBJC_CATEGORY_PROTOCOLS_$_",
7080 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007081
Fariborz Jahanian61186122012-02-17 18:40:41 +00007082 // Protocol's property metadata.
7083 std::vector<ObjCPropertyDecl *> ClassProperties;
7084 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7085 E = CDecl->prop_end(); I != E; ++I)
7086 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007087
Fariborz Jahanian61186122012-02-17 18:40:41 +00007088 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7089 /* Container */0,
7090 "_OBJC_$_PROP_LIST_",
7091 FullCategoryName);
7092
7093 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007094 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007095 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007096 InstanceMethods,
7097 ClassMethods,
7098 RefedProtocols,
7099 ClassProperties);
7100
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007101 // Determine if this category is also "non-lazy".
7102 if (ImplementationIsNonLazy(IDecl))
7103 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007104
7105}
7106
7107void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7108 int CatDefCount = CategoryImplementation.size();
7109 if (!CatDefCount)
7110 return;
7111 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7112 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7113 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7114 for (int i = 0; i < CatDefCount; i++) {
7115 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7116 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7117 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7118 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7119 Result += ClassDecl->getName();
7120 Result += "_$_";
7121 Result += CatDecl->getName();
7122 Result += ",\n";
7123 }
7124 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007125}
7126
7127// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7128/// class methods.
7129template<typename MethodIterator>
7130void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7131 MethodIterator MethodEnd,
7132 bool IsInstanceMethod,
7133 StringRef prefix,
7134 StringRef ClassName,
7135 std::string &Result) {
7136 if (MethodBegin == MethodEnd) return;
7137
7138 if (!objc_impl_method) {
7139 /* struct _objc_method {
7140 SEL _cmd;
7141 char *method_types;
7142 void *_imp;
7143 }
7144 */
7145 Result += "\nstruct _objc_method {\n";
7146 Result += "\tSEL _cmd;\n";
7147 Result += "\tchar *method_types;\n";
7148 Result += "\tvoid *_imp;\n";
7149 Result += "};\n";
7150
7151 objc_impl_method = true;
7152 }
7153
7154 // Build _objc_method_list for class's methods if needed
7155
7156 /* struct {
7157 struct _objc_method_list *next_method;
7158 int method_count;
7159 struct _objc_method method_list[];
7160 }
7161 */
7162 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007163 Result += "\n";
7164 if (LangOpts.MicrosoftExt) {
7165 if (IsInstanceMethod)
7166 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7167 else
7168 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7169 }
7170 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007171 Result += "\tstruct _objc_method_list *next_method;\n";
7172 Result += "\tint method_count;\n";
7173 Result += "\tstruct _objc_method method_list[";
7174 Result += utostr(NumMethods);
7175 Result += "];\n} _OBJC_";
7176 Result += prefix;
7177 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7178 Result += "_METHODS_";
7179 Result += ClassName;
7180 Result += " __attribute__ ((used, section (\"__OBJC, __";
7181 Result += IsInstanceMethod ? "inst" : "cls";
7182 Result += "_meth\")))= ";
7183 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7184
7185 Result += "\t,{{(SEL)\"";
7186 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7187 std::string MethodTypeString;
7188 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7189 Result += "\", \"";
7190 Result += MethodTypeString;
7191 Result += "\", (void *)";
7192 Result += MethodInternalNames[*MethodBegin];
7193 Result += "}\n";
7194 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7195 Result += "\t ,{(SEL)\"";
7196 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7197 std::string MethodTypeString;
7198 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7199 Result += "\", \"";
7200 Result += MethodTypeString;
7201 Result += "\", (void *)";
7202 Result += MethodInternalNames[*MethodBegin];
7203 Result += "}\n";
7204 }
7205 Result += "\t }\n};\n";
7206}
7207
7208Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7209 SourceRange OldRange = IV->getSourceRange();
7210 Expr *BaseExpr = IV->getBase();
7211
7212 // Rewrite the base, but without actually doing replaces.
7213 {
7214 DisableReplaceStmtScope S(*this);
7215 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7216 IV->setBase(BaseExpr);
7217 }
7218
7219 ObjCIvarDecl *D = IV->getDecl();
7220
7221 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007222
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007223 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7224 const ObjCInterfaceType *iFaceDecl =
7225 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7226 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7227 // lookup which class implements the instance variable.
7228 ObjCInterfaceDecl *clsDeclared = 0;
7229 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7230 clsDeclared);
7231 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7232
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007233 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007234 std::string IvarOffsetName;
7235 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7236
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007237 ReferencedIvars[clsDeclared].insert(D);
7238
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007239 // cast offset to "char *".
7240 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7241 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007242 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007243 BaseExpr);
7244 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7245 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7246 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007247 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7248 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007249 SourceLocation());
7250 BinaryOperator *addExpr =
7251 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7252 Context->getPointerType(Context->CharTy),
7253 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007254 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007255 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7256 SourceLocation(),
7257 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007258 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007259 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007260 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007261
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007262 castExpr = NoTypeInfoCStyleCastExpr(Context,
7263 castT,
7264 CK_BitCast,
7265 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007266 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007267 VK_LValue, OK_Ordinary,
7268 SourceLocation());
7269 PE = new (Context) ParenExpr(OldRange.getBegin(),
7270 OldRange.getEnd(),
7271 Exp);
7272
7273 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007274 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007275
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007276 ReplaceStmtWithRange(IV, Replacement, OldRange);
7277 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007278}