blob: b3d85a4ad39f8c32aad7da66e2dac98d79eb9902 [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
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002273// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002274void 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
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002314// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002315void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2316 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002317 SmallVector<QualType, 2> ArgTys;
2318 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002319 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002320 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002321 true /*isVariadic*/);
2322 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2323 SourceLocation(),
2324 SourceLocation(),
2325 msgSendIdent, msgSendType, 0,
2326 SC_Extern,
2327 SC_None, false);
2328}
2329
2330// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2331void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2332 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2333 SmallVector<QualType, 16> ArgTys;
2334 QualType argT = Context->getObjCIdType();
2335 assert(!argT.isNull() && "Can't find 'id' type");
2336 ArgTys.push_back(argT);
2337 argT = Context->getObjCSelType();
2338 assert(!argT.isNull() && "Can't find 'SEL' type");
2339 ArgTys.push_back(argT);
2340 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2341 &ArgTys[0], ArgTys.size(),
2342 true /*isVariadic*/);
2343 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2344 SourceLocation(),
2345 SourceLocation(),
2346 msgSendIdent, msgSendType, 0,
2347 SC_Extern,
2348 SC_None, false);
2349}
2350
2351// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002352// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002353void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2354 IdentifierInfo *msgSendIdent =
2355 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002356 SmallVector<QualType, 2> ArgTys;
2357 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002358 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002359 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002360 true /*isVariadic*/);
2361 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2362 SourceLocation(),
2363 SourceLocation(),
2364 msgSendIdent, msgSendType, 0,
2365 SC_Extern,
2366 SC_None, false);
2367}
2368
2369// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2370void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2371 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2372 SmallVector<QualType, 16> ArgTys;
2373 QualType argT = Context->getObjCIdType();
2374 assert(!argT.isNull() && "Can't find 'id' type");
2375 ArgTys.push_back(argT);
2376 argT = Context->getObjCSelType();
2377 assert(!argT.isNull() && "Can't find 'SEL' type");
2378 ArgTys.push_back(argT);
2379 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2380 &ArgTys[0], ArgTys.size(),
2381 true /*isVariadic*/);
2382 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2383 SourceLocation(),
2384 SourceLocation(),
2385 msgSendIdent, msgSendType, 0,
2386 SC_Extern,
2387 SC_None, false);
2388}
2389
2390// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2391void RewriteModernObjC::SynthGetClassFunctionDecl() {
2392 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2393 SmallVector<QualType, 16> ArgTys;
2394 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2395 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2396 &ArgTys[0], ArgTys.size());
2397 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2398 SourceLocation(),
2399 SourceLocation(),
2400 getClassIdent, getClassType, 0,
2401 SC_Extern,
2402 SC_None, false);
2403}
2404
2405// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2406void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2407 IdentifierInfo *getSuperClassIdent =
2408 &Context->Idents.get("class_getSuperclass");
2409 SmallVector<QualType, 16> ArgTys;
2410 ArgTys.push_back(Context->getObjCClassType());
2411 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2412 &ArgTys[0], ArgTys.size());
2413 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2414 SourceLocation(),
2415 SourceLocation(),
2416 getSuperClassIdent,
2417 getClassType, 0,
2418 SC_Extern,
2419 SC_None,
2420 false);
2421}
2422
2423// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2424void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2425 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2426 SmallVector<QualType, 16> ArgTys;
2427 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2428 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2429 &ArgTys[0], ArgTys.size());
2430 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2431 SourceLocation(),
2432 SourceLocation(),
2433 getClassIdent, getClassType, 0,
2434 SC_Extern,
2435 SC_None, false);
2436}
2437
2438Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2439 QualType strType = getConstantStringStructType();
2440
2441 std::string S = "__NSConstantStringImpl_";
2442
2443 std::string tmpName = InFileName;
2444 unsigned i;
2445 for (i=0; i < tmpName.length(); i++) {
2446 char c = tmpName.at(i);
2447 // replace any non alphanumeric characters with '_'.
2448 if (!isalpha(c) && (c < '0' || c > '9'))
2449 tmpName[i] = '_';
2450 }
2451 S += tmpName;
2452 S += "_";
2453 S += utostr(NumObjCStringLiterals++);
2454
2455 Preamble += "static __NSConstantStringImpl " + S;
2456 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2457 Preamble += "0x000007c8,"; // utf8_str
2458 // The pretty printer for StringLiteral handles escape characters properly.
2459 std::string prettyBufS;
2460 llvm::raw_string_ostream prettyBuf(prettyBufS);
2461 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2462 PrintingPolicy(LangOpts));
2463 Preamble += prettyBuf.str();
2464 Preamble += ",";
2465 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2466
2467 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2468 SourceLocation(), &Context->Idents.get(S),
2469 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002470 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002471 SourceLocation());
2472 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2473 Context->getPointerType(DRE->getType()),
2474 VK_RValue, OK_Ordinary,
2475 SourceLocation());
2476 // cast to NSConstantString *
2477 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2478 CK_CPointerToObjCPointerCast, Unop);
2479 ReplaceStmt(Exp, cast);
2480 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2481 return cast;
2482}
2483
Fariborz Jahanian55947042012-03-27 20:17:30 +00002484Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2485 unsigned IntSize =
2486 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2487
2488 Expr *FlagExp = IntegerLiteral::Create(*Context,
2489 llvm::APInt(IntSize, Exp->getValue()),
2490 Context->IntTy, Exp->getLocation());
2491 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2492 CK_BitCast, FlagExp);
2493 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2494 cast);
2495 ReplaceStmt(Exp, PE);
2496 return PE;
2497}
2498
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002499Stmt *RewriteModernObjC::RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp) {
2500 // synthesize declaration of helper functions needed in this routine.
2501 if (!SelGetUidFunctionDecl)
2502 SynthSelGetUidFunctionDecl();
2503 // use objc_msgSend() for all.
2504 if (!MsgSendFunctionDecl)
2505 SynthMsgSendFunctionDecl();
2506 if (!GetClassFunctionDecl)
2507 SynthGetClassFunctionDecl();
2508
2509 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2510 SourceLocation StartLoc = Exp->getLocStart();
2511 SourceLocation EndLoc = Exp->getLocEnd();
2512
2513 // Synthesize a call to objc_msgSend().
2514 SmallVector<Expr*, 4> MsgExprs;
2515 SmallVector<Expr*, 4> ClsExprs;
2516 QualType argType = Context->getPointerType(Context->CharTy);
2517 QualType expType = Exp->getType();
2518
2519 // Create a call to objc_getClass("NSNumber"). It will be th 1st argument.
2520 ObjCInterfaceDecl *Class =
2521 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2522
2523 IdentifierInfo *clsName = Class->getIdentifier();
2524 ClsExprs.push_back(StringLiteral::Create(*Context,
2525 clsName->getName(),
2526 StringLiteral::Ascii, false,
2527 argType, SourceLocation()));
2528 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2529 &ClsExprs[0],
2530 ClsExprs.size(),
2531 StartLoc, EndLoc);
2532 MsgExprs.push_back(Cls);
2533
2534 // Create a call to sel_registerName("numberWithBool:"), etc.
2535 // it will be the 2nd argument.
2536 SmallVector<Expr*, 4> SelExprs;
2537 ObjCMethodDecl *NumericMethod = Exp->getObjCNumericLiteralMethod();
2538 SelExprs.push_back(StringLiteral::Create(*Context,
2539 NumericMethod->getSelector().getAsString(),
2540 StringLiteral::Ascii, false,
2541 argType, SourceLocation()));
2542 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2543 &SelExprs[0], SelExprs.size(),
2544 StartLoc, EndLoc);
2545 MsgExprs.push_back(SelExp);
2546
2547 // User provided numeric literal is the 3rd, and last, argument.
2548 Expr *userExpr = Exp->getNumber();
2549 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2550 QualType type = ICE->getType();
2551 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2552 CastKind CK = CK_BitCast;
2553 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2554 CK = CK_IntegralToBoolean;
2555 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2556 }
2557 MsgExprs.push_back(userExpr);
2558
2559 SmallVector<QualType, 4> ArgTypes;
2560 ArgTypes.push_back(Context->getObjCIdType());
2561 ArgTypes.push_back(Context->getObjCSelType());
2562 for (ObjCMethodDecl::param_iterator PI = NumericMethod->param_begin(),
2563 E = NumericMethod->param_end(); PI != E; ++PI)
2564 ArgTypes.push_back((*PI)->getType());
2565
2566 QualType returnType = Exp->getType();
2567 // Get the type, we will need to reference it in a couple spots.
2568 QualType msgSendType = MsgSendFlavor->getType();
2569
2570 // Create a reference to the objc_msgSend() declaration.
2571 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2572 VK_LValue, SourceLocation());
2573
2574 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2575 Context->getPointerType(Context->VoidTy),
2576 CK_BitCast, DRE);
2577
2578 // Now do the "normal" pointer to function cast.
2579 QualType castType =
2580 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2581 NumericMethod->isVariadic());
2582 castType = Context->getPointerType(castType);
2583 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2584 cast);
2585
2586 // Don't forget the parens to enforce the proper binding.
2587 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2588
2589 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2590 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2591 MsgExprs.size(),
2592 FT->getResultType(), VK_RValue,
2593 EndLoc);
2594 ReplaceStmt(Exp, CE);
2595 return CE;
2596}
2597
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002598Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2599 // synthesize declaration of helper functions needed in this routine.
2600 if (!SelGetUidFunctionDecl)
2601 SynthSelGetUidFunctionDecl();
2602 // use objc_msgSend() for all.
2603 if (!MsgSendFunctionDecl)
2604 SynthMsgSendFunctionDecl();
2605 if (!GetClassFunctionDecl)
2606 SynthGetClassFunctionDecl();
2607
2608 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2609 SourceLocation StartLoc = Exp->getLocStart();
2610 SourceLocation EndLoc = Exp->getLocEnd();
2611
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002612 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002613 QualType IntQT = Context->IntTy;
2614 QualType NSArrayFType =
2615 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002616 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002617 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2618 DeclRefExpr *NSArrayDRE =
2619 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2620 SourceLocation());
2621
2622 SmallVector<Expr*, 16> InitExprs;
2623 unsigned NumElements = Exp->getNumElements();
2624 unsigned UnsignedIntSize =
2625 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2626 Expr *count = IntegerLiteral::Create(*Context,
2627 llvm::APInt(UnsignedIntSize, NumElements),
2628 Context->UnsignedIntTy, SourceLocation());
2629 InitExprs.push_back(count);
2630 for (unsigned i = 0; i < NumElements; i++)
2631 InitExprs.push_back(Exp->getElement(i));
2632 Expr *NSArrayCallExpr =
2633 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2634 NSArrayFType, VK_LValue, SourceLocation());
2635
2636 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2637 SourceLocation(),
2638 &Context->Idents.get("arr"),
2639 Context->getPointerType(Context->VoidPtrTy), 0,
2640 /*BitWidth=*/0, /*Mutable=*/true,
2641 /*HasInit=*/false);
2642 MemberExpr *ArrayLiteralME =
2643 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2644 SourceLocation(),
2645 ARRFD->getType(), VK_LValue,
2646 OK_Ordinary);
2647 QualType ConstIdT = Context->getObjCIdType().withConst();
2648 CStyleCastExpr * ArrayLiteralObjects =
2649 NoTypeInfoCStyleCastExpr(Context,
2650 Context->getPointerType(ConstIdT),
2651 CK_BitCast,
2652 ArrayLiteralME);
2653
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002654 // Synthesize a call to objc_msgSend().
2655 SmallVector<Expr*, 32> MsgExprs;
2656 SmallVector<Expr*, 4> ClsExprs;
2657 QualType argType = Context->getPointerType(Context->CharTy);
2658 QualType expType = Exp->getType();
2659
2660 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2661 ObjCInterfaceDecl *Class =
2662 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2663
2664 IdentifierInfo *clsName = Class->getIdentifier();
2665 ClsExprs.push_back(StringLiteral::Create(*Context,
2666 clsName->getName(),
2667 StringLiteral::Ascii, false,
2668 argType, SourceLocation()));
2669 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2670 &ClsExprs[0],
2671 ClsExprs.size(),
2672 StartLoc, EndLoc);
2673 MsgExprs.push_back(Cls);
2674
2675 // Create a call to sel_registerName("arrayWithObjects:count:").
2676 // it will be the 2nd argument.
2677 SmallVector<Expr*, 4> SelExprs;
2678 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2679 SelExprs.push_back(StringLiteral::Create(*Context,
2680 ArrayMethod->getSelector().getAsString(),
2681 StringLiteral::Ascii, false,
2682 argType, SourceLocation()));
2683 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2684 &SelExprs[0], SelExprs.size(),
2685 StartLoc, EndLoc);
2686 MsgExprs.push_back(SelExp);
2687
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002688 // (const id [])objects
2689 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002690
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002691 // (NSUInteger)cnt
2692 Expr *cnt = IntegerLiteral::Create(*Context,
2693 llvm::APInt(UnsignedIntSize, NumElements),
2694 Context->UnsignedIntTy, SourceLocation());
2695 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002696
2697
2698 SmallVector<QualType, 4> ArgTypes;
2699 ArgTypes.push_back(Context->getObjCIdType());
2700 ArgTypes.push_back(Context->getObjCSelType());
2701 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2702 E = ArrayMethod->param_end(); PI != E; ++PI)
2703 ArgTypes.push_back((*PI)->getType());
2704
2705 QualType returnType = Exp->getType();
2706 // Get the type, we will need to reference it in a couple spots.
2707 QualType msgSendType = MsgSendFlavor->getType();
2708
2709 // Create a reference to the objc_msgSend() declaration.
2710 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2711 VK_LValue, SourceLocation());
2712
2713 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2714 Context->getPointerType(Context->VoidTy),
2715 CK_BitCast, DRE);
2716
2717 // Now do the "normal" pointer to function cast.
2718 QualType castType =
2719 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2720 ArrayMethod->isVariadic());
2721 castType = Context->getPointerType(castType);
2722 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2723 cast);
2724
2725 // Don't forget the parens to enforce the proper binding.
2726 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2727
2728 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2729 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2730 MsgExprs.size(),
2731 FT->getResultType(), VK_RValue,
2732 EndLoc);
2733 ReplaceStmt(Exp, CE);
2734 return CE;
2735}
2736
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002737Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2738 // synthesize declaration of helper functions needed in this routine.
2739 if (!SelGetUidFunctionDecl)
2740 SynthSelGetUidFunctionDecl();
2741 // use objc_msgSend() for all.
2742 if (!MsgSendFunctionDecl)
2743 SynthMsgSendFunctionDecl();
2744 if (!GetClassFunctionDecl)
2745 SynthGetClassFunctionDecl();
2746
2747 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2748 SourceLocation StartLoc = Exp->getLocStart();
2749 SourceLocation EndLoc = Exp->getLocEnd();
2750
2751 // Build the expression: __NSContainer_literal(int, ...).arr
2752 QualType IntQT = Context->IntTy;
2753 QualType NSDictFType =
2754 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2755 std::string NSDictFName("__NSContainer_literal");
2756 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2757 DeclRefExpr *NSDictDRE =
2758 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2759 SourceLocation());
2760
2761 SmallVector<Expr*, 16> KeyExprs;
2762 SmallVector<Expr*, 16> ValueExprs;
2763
2764 unsigned NumElements = Exp->getNumElements();
2765 unsigned UnsignedIntSize =
2766 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2767 Expr *count = IntegerLiteral::Create(*Context,
2768 llvm::APInt(UnsignedIntSize, NumElements),
2769 Context->UnsignedIntTy, SourceLocation());
2770 KeyExprs.push_back(count);
2771 ValueExprs.push_back(count);
2772 for (unsigned i = 0; i < NumElements; i++) {
2773 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2774 KeyExprs.push_back(Element.Key);
2775 ValueExprs.push_back(Element.Value);
2776 }
2777
2778 // (const id [])objects
2779 Expr *NSValueCallExpr =
2780 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2781 NSDictFType, VK_LValue, SourceLocation());
2782
2783 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2784 SourceLocation(),
2785 &Context->Idents.get("arr"),
2786 Context->getPointerType(Context->VoidPtrTy), 0,
2787 /*BitWidth=*/0, /*Mutable=*/true,
2788 /*HasInit=*/false);
2789 MemberExpr *DictLiteralValueME =
2790 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2791 SourceLocation(),
2792 ARRFD->getType(), VK_LValue,
2793 OK_Ordinary);
2794 QualType ConstIdT = Context->getObjCIdType().withConst();
2795 CStyleCastExpr * DictValueObjects =
2796 NoTypeInfoCStyleCastExpr(Context,
2797 Context->getPointerType(ConstIdT),
2798 CK_BitCast,
2799 DictLiteralValueME);
2800 // (const id <NSCopying> [])keys
2801 Expr *NSKeyCallExpr =
2802 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2803 NSDictFType, VK_LValue, SourceLocation());
2804
2805 MemberExpr *DictLiteralKeyME =
2806 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2807 SourceLocation(),
2808 ARRFD->getType(), VK_LValue,
2809 OK_Ordinary);
2810
2811 CStyleCastExpr * DictKeyObjects =
2812 NoTypeInfoCStyleCastExpr(Context,
2813 Context->getPointerType(ConstIdT),
2814 CK_BitCast,
2815 DictLiteralKeyME);
2816
2817
2818
2819 // Synthesize a call to objc_msgSend().
2820 SmallVector<Expr*, 32> MsgExprs;
2821 SmallVector<Expr*, 4> ClsExprs;
2822 QualType argType = Context->getPointerType(Context->CharTy);
2823 QualType expType = Exp->getType();
2824
2825 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2826 ObjCInterfaceDecl *Class =
2827 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2828
2829 IdentifierInfo *clsName = Class->getIdentifier();
2830 ClsExprs.push_back(StringLiteral::Create(*Context,
2831 clsName->getName(),
2832 StringLiteral::Ascii, false,
2833 argType, SourceLocation()));
2834 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2835 &ClsExprs[0],
2836 ClsExprs.size(),
2837 StartLoc, EndLoc);
2838 MsgExprs.push_back(Cls);
2839
2840 // Create a call to sel_registerName("arrayWithObjects:count:").
2841 // it will be the 2nd argument.
2842 SmallVector<Expr*, 4> SelExprs;
2843 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2844 SelExprs.push_back(StringLiteral::Create(*Context,
2845 DictMethod->getSelector().getAsString(),
2846 StringLiteral::Ascii, false,
2847 argType, SourceLocation()));
2848 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2849 &SelExprs[0], SelExprs.size(),
2850 StartLoc, EndLoc);
2851 MsgExprs.push_back(SelExp);
2852
2853 // (const id [])objects
2854 MsgExprs.push_back(DictValueObjects);
2855
2856 // (const id <NSCopying> [])keys
2857 MsgExprs.push_back(DictKeyObjects);
2858
2859 // (NSUInteger)cnt
2860 Expr *cnt = IntegerLiteral::Create(*Context,
2861 llvm::APInt(UnsignedIntSize, NumElements),
2862 Context->UnsignedIntTy, SourceLocation());
2863 MsgExprs.push_back(cnt);
2864
2865
2866 SmallVector<QualType, 8> ArgTypes;
2867 ArgTypes.push_back(Context->getObjCIdType());
2868 ArgTypes.push_back(Context->getObjCSelType());
2869 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2870 E = DictMethod->param_end(); PI != E; ++PI) {
2871 QualType T = (*PI)->getType();
2872 if (const PointerType* PT = T->getAs<PointerType>()) {
2873 QualType PointeeTy = PT->getPointeeType();
2874 convertToUnqualifiedObjCType(PointeeTy);
2875 T = Context->getPointerType(PointeeTy);
2876 }
2877 ArgTypes.push_back(T);
2878 }
2879
2880 QualType returnType = Exp->getType();
2881 // Get the type, we will need to reference it in a couple spots.
2882 QualType msgSendType = MsgSendFlavor->getType();
2883
2884 // Create a reference to the objc_msgSend() declaration.
2885 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2886 VK_LValue, SourceLocation());
2887
2888 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2889 Context->getPointerType(Context->VoidTy),
2890 CK_BitCast, DRE);
2891
2892 // Now do the "normal" pointer to function cast.
2893 QualType castType =
2894 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2895 DictMethod->isVariadic());
2896 castType = Context->getPointerType(castType);
2897 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2898 cast);
2899
2900 // Don't forget the parens to enforce the proper binding.
2901 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2902
2903 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2904 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2905 MsgExprs.size(),
2906 FT->getResultType(), VK_RValue,
2907 EndLoc);
2908 ReplaceStmt(Exp, CE);
2909 return CE;
2910}
2911
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002912// struct __rw_objc_super {
2913// struct objc_object *object; struct objc_object *superClass;
2914// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002915QualType RewriteModernObjC::getSuperStructType() {
2916 if (!SuperStructDecl) {
2917 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2918 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002919 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002920 QualType FieldTypes[2];
2921
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002922 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002923 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002924 // struct objc_object *superClass;
2925 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002926
2927 // Create fields
2928 for (unsigned i = 0; i < 2; ++i) {
2929 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2930 SourceLocation(),
2931 SourceLocation(), 0,
2932 FieldTypes[i], 0,
2933 /*BitWidth=*/0,
2934 /*Mutable=*/false,
2935 /*HasInit=*/false));
2936 }
2937
2938 SuperStructDecl->completeDefinition();
2939 }
2940 return Context->getTagDeclType(SuperStructDecl);
2941}
2942
2943QualType RewriteModernObjC::getConstantStringStructType() {
2944 if (!ConstantStringDecl) {
2945 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2946 SourceLocation(), SourceLocation(),
2947 &Context->Idents.get("__NSConstantStringImpl"));
2948 QualType FieldTypes[4];
2949
2950 // struct objc_object *receiver;
2951 FieldTypes[0] = Context->getObjCIdType();
2952 // int flags;
2953 FieldTypes[1] = Context->IntTy;
2954 // char *str;
2955 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2956 // long length;
2957 FieldTypes[3] = Context->LongTy;
2958
2959 // Create fields
2960 for (unsigned i = 0; i < 4; ++i) {
2961 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2962 ConstantStringDecl,
2963 SourceLocation(),
2964 SourceLocation(), 0,
2965 FieldTypes[i], 0,
2966 /*BitWidth=*/0,
2967 /*Mutable=*/true,
2968 /*HasInit=*/false));
2969 }
2970
2971 ConstantStringDecl->completeDefinition();
2972 }
2973 return Context->getTagDeclType(ConstantStringDecl);
2974}
2975
2976Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2977 SourceLocation StartLoc,
2978 SourceLocation EndLoc) {
2979 if (!SelGetUidFunctionDecl)
2980 SynthSelGetUidFunctionDecl();
2981 if (!MsgSendFunctionDecl)
2982 SynthMsgSendFunctionDecl();
2983 if (!MsgSendSuperFunctionDecl)
2984 SynthMsgSendSuperFunctionDecl();
2985 if (!MsgSendStretFunctionDecl)
2986 SynthMsgSendStretFunctionDecl();
2987 if (!MsgSendSuperStretFunctionDecl)
2988 SynthMsgSendSuperStretFunctionDecl();
2989 if (!MsgSendFpretFunctionDecl)
2990 SynthMsgSendFpretFunctionDecl();
2991 if (!GetClassFunctionDecl)
2992 SynthGetClassFunctionDecl();
2993 if (!GetSuperClassFunctionDecl)
2994 SynthGetSuperClassFunctionDecl();
2995 if (!GetMetaClassFunctionDecl)
2996 SynthGetMetaClassFunctionDecl();
2997
2998 // default to objc_msgSend().
2999 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3000 // May need to use objc_msgSend_stret() as well.
3001 FunctionDecl *MsgSendStretFlavor = 0;
3002 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3003 QualType resultType = mDecl->getResultType();
3004 if (resultType->isRecordType())
3005 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3006 else if (resultType->isRealFloatingType())
3007 MsgSendFlavor = MsgSendFpretFunctionDecl;
3008 }
3009
3010 // Synthesize a call to objc_msgSend().
3011 SmallVector<Expr*, 8> MsgExprs;
3012 switch (Exp->getReceiverKind()) {
3013 case ObjCMessageExpr::SuperClass: {
3014 MsgSendFlavor = MsgSendSuperFunctionDecl;
3015 if (MsgSendStretFlavor)
3016 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3017 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3018
3019 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3020
3021 SmallVector<Expr*, 4> InitExprs;
3022
3023 // set the receiver to self, the first argument to all methods.
3024 InitExprs.push_back(
3025 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3026 CK_BitCast,
3027 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003028 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003029 Context->getObjCIdType(),
3030 VK_RValue,
3031 SourceLocation()))
3032 ); // set the 'receiver'.
3033
3034 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3035 SmallVector<Expr*, 8> ClsExprs;
3036 QualType argType = Context->getPointerType(Context->CharTy);
3037 ClsExprs.push_back(StringLiteral::Create(*Context,
3038 ClassDecl->getIdentifier()->getName(),
3039 StringLiteral::Ascii, false,
3040 argType, SourceLocation()));
3041 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3042 &ClsExprs[0],
3043 ClsExprs.size(),
3044 StartLoc,
3045 EndLoc);
3046 // (Class)objc_getClass("CurrentClass")
3047 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3048 Context->getObjCClassType(),
3049 CK_BitCast, Cls);
3050 ClsExprs.clear();
3051 ClsExprs.push_back(ArgExpr);
3052 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3053 &ClsExprs[0], ClsExprs.size(),
3054 StartLoc, EndLoc);
3055
3056 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3057 // To turn off a warning, type-cast to 'id'
3058 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3059 NoTypeInfoCStyleCastExpr(Context,
3060 Context->getObjCIdType(),
3061 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003062 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003063 QualType superType = getSuperStructType();
3064 Expr *SuperRep;
3065
3066 if (LangOpts.MicrosoftExt) {
3067 SynthSuperContructorFunctionDecl();
3068 // Simulate a contructor call...
3069 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003070 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003071 SourceLocation());
3072 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3073 InitExprs.size(),
3074 superType, VK_LValue,
3075 SourceLocation());
3076 // The code for super is a little tricky to prevent collision with
3077 // the structure definition in the header. The rewriter has it's own
3078 // internal definition (__rw_objc_super) that is uses. This is why
3079 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003080 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003081 //
3082 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3083 Context->getPointerType(SuperRep->getType()),
3084 VK_RValue, OK_Ordinary,
3085 SourceLocation());
3086 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3087 Context->getPointerType(superType),
3088 CK_BitCast, SuperRep);
3089 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003090 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003091 InitListExpr *ILE =
3092 new (Context) InitListExpr(*Context, SourceLocation(),
3093 &InitExprs[0], InitExprs.size(),
3094 SourceLocation());
3095 TypeSourceInfo *superTInfo
3096 = Context->getTrivialTypeSourceInfo(superType);
3097 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3098 superType, VK_LValue,
3099 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003100 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003101 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3102 Context->getPointerType(SuperRep->getType()),
3103 VK_RValue, OK_Ordinary,
3104 SourceLocation());
3105 }
3106 MsgExprs.push_back(SuperRep);
3107 break;
3108 }
3109
3110 case ObjCMessageExpr::Class: {
3111 SmallVector<Expr*, 8> ClsExprs;
3112 QualType argType = Context->getPointerType(Context->CharTy);
3113 ObjCInterfaceDecl *Class
3114 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3115 IdentifierInfo *clsName = Class->getIdentifier();
3116 ClsExprs.push_back(StringLiteral::Create(*Context,
3117 clsName->getName(),
3118 StringLiteral::Ascii, false,
3119 argType, SourceLocation()));
3120 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3121 &ClsExprs[0],
3122 ClsExprs.size(),
3123 StartLoc, EndLoc);
3124 MsgExprs.push_back(Cls);
3125 break;
3126 }
3127
3128 case ObjCMessageExpr::SuperInstance:{
3129 MsgSendFlavor = MsgSendSuperFunctionDecl;
3130 if (MsgSendStretFlavor)
3131 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3132 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3133 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3134 SmallVector<Expr*, 4> InitExprs;
3135
3136 InitExprs.push_back(
3137 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3138 CK_BitCast,
3139 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003140 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003141 Context->getObjCIdType(),
3142 VK_RValue, SourceLocation()))
3143 ); // set the 'receiver'.
3144
3145 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3146 SmallVector<Expr*, 8> ClsExprs;
3147 QualType argType = Context->getPointerType(Context->CharTy);
3148 ClsExprs.push_back(StringLiteral::Create(*Context,
3149 ClassDecl->getIdentifier()->getName(),
3150 StringLiteral::Ascii, false, argType,
3151 SourceLocation()));
3152 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3153 &ClsExprs[0],
3154 ClsExprs.size(),
3155 StartLoc, EndLoc);
3156 // (Class)objc_getClass("CurrentClass")
3157 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3158 Context->getObjCClassType(),
3159 CK_BitCast, Cls);
3160 ClsExprs.clear();
3161 ClsExprs.push_back(ArgExpr);
3162 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3163 &ClsExprs[0], ClsExprs.size(),
3164 StartLoc, EndLoc);
3165
3166 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3167 // To turn off a warning, type-cast to 'id'
3168 InitExprs.push_back(
3169 // set 'super class', using class_getSuperclass().
3170 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3171 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003172 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003173 QualType superType = getSuperStructType();
3174 Expr *SuperRep;
3175
3176 if (LangOpts.MicrosoftExt) {
3177 SynthSuperContructorFunctionDecl();
3178 // Simulate a contructor call...
3179 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003180 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003181 SourceLocation());
3182 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3183 InitExprs.size(),
3184 superType, VK_LValue, SourceLocation());
3185 // The code for super is a little tricky to prevent collision with
3186 // the structure definition in the header. The rewriter has it's own
3187 // internal definition (__rw_objc_super) that is uses. This is why
3188 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003189 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003190 //
3191 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3192 Context->getPointerType(SuperRep->getType()),
3193 VK_RValue, OK_Ordinary,
3194 SourceLocation());
3195 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3196 Context->getPointerType(superType),
3197 CK_BitCast, SuperRep);
3198 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003199 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003200 InitListExpr *ILE =
3201 new (Context) InitListExpr(*Context, SourceLocation(),
3202 &InitExprs[0], InitExprs.size(),
3203 SourceLocation());
3204 TypeSourceInfo *superTInfo
3205 = Context->getTrivialTypeSourceInfo(superType);
3206 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3207 superType, VK_RValue, ILE,
3208 false);
3209 }
3210 MsgExprs.push_back(SuperRep);
3211 break;
3212 }
3213
3214 case ObjCMessageExpr::Instance: {
3215 // Remove all type-casts because it may contain objc-style types; e.g.
3216 // Foo<Proto> *.
3217 Expr *recExpr = Exp->getInstanceReceiver();
3218 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3219 recExpr = CE->getSubExpr();
3220 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3221 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3222 ? CK_BlockPointerToObjCPointerCast
3223 : CK_CPointerToObjCPointerCast;
3224
3225 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3226 CK, recExpr);
3227 MsgExprs.push_back(recExpr);
3228 break;
3229 }
3230 }
3231
3232 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3233 SmallVector<Expr*, 8> SelExprs;
3234 QualType argType = Context->getPointerType(Context->CharTy);
3235 SelExprs.push_back(StringLiteral::Create(*Context,
3236 Exp->getSelector().getAsString(),
3237 StringLiteral::Ascii, false,
3238 argType, SourceLocation()));
3239 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3240 &SelExprs[0], SelExprs.size(),
3241 StartLoc,
3242 EndLoc);
3243 MsgExprs.push_back(SelExp);
3244
3245 // Now push any user supplied arguments.
3246 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3247 Expr *userExpr = Exp->getArg(i);
3248 // Make all implicit casts explicit...ICE comes in handy:-)
3249 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3250 // Reuse the ICE type, it is exactly what the doctor ordered.
3251 QualType type = ICE->getType();
3252 if (needToScanForQualifiers(type))
3253 type = Context->getObjCIdType();
3254 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3255 (void)convertBlockPointerToFunctionPointer(type);
3256 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3257 CastKind CK;
3258 if (SubExpr->getType()->isIntegralType(*Context) &&
3259 type->isBooleanType()) {
3260 CK = CK_IntegralToBoolean;
3261 } else if (type->isObjCObjectPointerType()) {
3262 if (SubExpr->getType()->isBlockPointerType()) {
3263 CK = CK_BlockPointerToObjCPointerCast;
3264 } else if (SubExpr->getType()->isPointerType()) {
3265 CK = CK_CPointerToObjCPointerCast;
3266 } else {
3267 CK = CK_BitCast;
3268 }
3269 } else {
3270 CK = CK_BitCast;
3271 }
3272
3273 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3274 }
3275 // Make id<P...> cast into an 'id' cast.
3276 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3277 if (CE->getType()->isObjCQualifiedIdType()) {
3278 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3279 userExpr = CE->getSubExpr();
3280 CastKind CK;
3281 if (userExpr->getType()->isIntegralType(*Context)) {
3282 CK = CK_IntegralToPointer;
3283 } else if (userExpr->getType()->isBlockPointerType()) {
3284 CK = CK_BlockPointerToObjCPointerCast;
3285 } else if (userExpr->getType()->isPointerType()) {
3286 CK = CK_CPointerToObjCPointerCast;
3287 } else {
3288 CK = CK_BitCast;
3289 }
3290 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3291 CK, userExpr);
3292 }
3293 }
3294 MsgExprs.push_back(userExpr);
3295 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3296 // out the argument in the original expression (since we aren't deleting
3297 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3298 //Exp->setArg(i, 0);
3299 }
3300 // Generate the funky cast.
3301 CastExpr *cast;
3302 SmallVector<QualType, 8> ArgTypes;
3303 QualType returnType;
3304
3305 // Push 'id' and 'SEL', the 2 implicit arguments.
3306 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3307 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3308 else
3309 ArgTypes.push_back(Context->getObjCIdType());
3310 ArgTypes.push_back(Context->getObjCSelType());
3311 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3312 // Push any user argument types.
3313 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3314 E = OMD->param_end(); PI != E; ++PI) {
3315 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3316 ? Context->getObjCIdType()
3317 : (*PI)->getType();
3318 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3319 (void)convertBlockPointerToFunctionPointer(t);
3320 ArgTypes.push_back(t);
3321 }
3322 returnType = Exp->getType();
3323 convertToUnqualifiedObjCType(returnType);
3324 (void)convertBlockPointerToFunctionPointer(returnType);
3325 } else {
3326 returnType = Context->getObjCIdType();
3327 }
3328 // Get the type, we will need to reference it in a couple spots.
3329 QualType msgSendType = MsgSendFlavor->getType();
3330
3331 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003332 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003333 VK_LValue, SourceLocation());
3334
3335 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3336 // If we don't do this cast, we get the following bizarre warning/note:
3337 // xx.m:13: warning: function called through a non-compatible type
3338 // xx.m:13: note: if this code is reached, the program will abort
3339 cast = NoTypeInfoCStyleCastExpr(Context,
3340 Context->getPointerType(Context->VoidTy),
3341 CK_BitCast, DRE);
3342
3343 // Now do the "normal" pointer to function cast.
3344 QualType castType =
3345 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3346 // If we don't have a method decl, force a variadic cast.
3347 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3348 castType = Context->getPointerType(castType);
3349 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3350 cast);
3351
3352 // Don't forget the parens to enforce the proper binding.
3353 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3354
3355 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3356 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3357 MsgExprs.size(),
3358 FT->getResultType(), VK_RValue,
3359 EndLoc);
3360 Stmt *ReplacingStmt = CE;
3361 if (MsgSendStretFlavor) {
3362 // We have the method which returns a struct/union. Must also generate
3363 // call to objc_msgSend_stret and hang both varieties on a conditional
3364 // expression which dictate which one to envoke depending on size of
3365 // method's return type.
3366
3367 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003368 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3369 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003370 VK_LValue, SourceLocation());
3371 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3372 cast = NoTypeInfoCStyleCastExpr(Context,
3373 Context->getPointerType(Context->VoidTy),
3374 CK_BitCast, STDRE);
3375 // Now do the "normal" pointer to function cast.
3376 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3377 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3378 castType = Context->getPointerType(castType);
3379 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3380 cast);
3381
3382 // Don't forget the parens to enforce the proper binding.
3383 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3384
3385 FT = msgSendType->getAs<FunctionType>();
3386 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3387 MsgExprs.size(),
3388 FT->getResultType(), VK_RValue,
3389 SourceLocation());
3390
3391 // Build sizeof(returnType)
3392 UnaryExprOrTypeTraitExpr *sizeofExpr =
3393 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3394 Context->getTrivialTypeSourceInfo(returnType),
3395 Context->getSizeType(), SourceLocation(),
3396 SourceLocation());
3397 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3398 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3399 // For X86 it is more complicated and some kind of target specific routine
3400 // is needed to decide what to do.
3401 unsigned IntSize =
3402 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3403 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3404 llvm::APInt(IntSize, 8),
3405 Context->IntTy,
3406 SourceLocation());
3407 BinaryOperator *lessThanExpr =
3408 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3409 VK_RValue, OK_Ordinary, SourceLocation());
3410 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3411 ConditionalOperator *CondExpr =
3412 new (Context) ConditionalOperator(lessThanExpr,
3413 SourceLocation(), CE,
3414 SourceLocation(), STCE,
3415 returnType, VK_RValue, OK_Ordinary);
3416 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3417 CondExpr);
3418 }
3419 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3420 return ReplacingStmt;
3421}
3422
3423Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3424 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3425 Exp->getLocEnd());
3426
3427 // Now do the actual rewrite.
3428 ReplaceStmt(Exp, ReplacingStmt);
3429
3430 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3431 return ReplacingStmt;
3432}
3433
3434// typedef struct objc_object Protocol;
3435QualType RewriteModernObjC::getProtocolType() {
3436 if (!ProtocolTypeDecl) {
3437 TypeSourceInfo *TInfo
3438 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3439 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3440 SourceLocation(), SourceLocation(),
3441 &Context->Idents.get("Protocol"),
3442 TInfo);
3443 }
3444 return Context->getTypeDeclType(ProtocolTypeDecl);
3445}
3446
3447/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3448/// a synthesized/forward data reference (to the protocol's metadata).
3449/// The forward references (and metadata) are generated in
3450/// RewriteModernObjC::HandleTranslationUnit().
3451Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003452 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3453 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003454 IdentifierInfo *ID = &Context->Idents.get(Name);
3455 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3456 SourceLocation(), ID, getProtocolType(), 0,
3457 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003458 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3459 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003460 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3461 Context->getPointerType(DRE->getType()),
3462 VK_RValue, OK_Ordinary, SourceLocation());
3463 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3464 CK_BitCast,
3465 DerefExpr);
3466 ReplaceStmt(Exp, castExpr);
3467 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3468 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3469 return castExpr;
3470
3471}
3472
3473bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3474 const char *endBuf) {
3475 while (startBuf < endBuf) {
3476 if (*startBuf == '#') {
3477 // Skip whitespace.
3478 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3479 ;
3480 if (!strncmp(startBuf, "if", strlen("if")) ||
3481 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3482 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3483 !strncmp(startBuf, "define", strlen("define")) ||
3484 !strncmp(startBuf, "undef", strlen("undef")) ||
3485 !strncmp(startBuf, "else", strlen("else")) ||
3486 !strncmp(startBuf, "elif", strlen("elif")) ||
3487 !strncmp(startBuf, "endif", strlen("endif")) ||
3488 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3489 !strncmp(startBuf, "include", strlen("include")) ||
3490 !strncmp(startBuf, "import", strlen("import")) ||
3491 !strncmp(startBuf, "include_next", strlen("include_next")))
3492 return true;
3493 }
3494 startBuf++;
3495 }
3496 return false;
3497}
3498
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003499/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003500/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003501bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3502 std::string &Result) {
3503 if (Type->isArrayType()) {
3504 QualType ElemTy = Context->getBaseElementType(Type);
3505 return RewriteObjCFieldDeclType(ElemTy, Result);
3506 }
3507 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003508 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3509 if (RD->isCompleteDefinition()) {
3510 if (RD->isStruct())
3511 Result += "\n\tstruct ";
3512 else if (RD->isUnion())
3513 Result += "\n\tunion ";
3514 else
3515 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003516
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003517 Result += RD->getName();
3518 if (TagsDefinedInIvarDecls.count(RD)) {
3519 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003520 Result += " ";
3521 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003522 }
3523 TagsDefinedInIvarDecls.insert(RD);
3524 Result += " {\n";
3525 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003526 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003527 FieldDecl *FD = *i;
3528 RewriteObjCFieldDecl(FD, Result);
3529 }
3530 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003531 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003532 }
3533 }
3534 else if (Type->isEnumeralType()) {
3535 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3536 if (ED->isCompleteDefinition()) {
3537 Result += "\n\tenum ";
3538 Result += ED->getName();
3539 if (TagsDefinedInIvarDecls.count(ED)) {
3540 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003541 Result += " ";
3542 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003543 }
3544 TagsDefinedInIvarDecls.insert(ED);
3545
3546 Result += " {\n";
3547 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3548 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3549 Result += "\t"; Result += EC->getName(); Result += " = ";
3550 llvm::APSInt Val = EC->getInitVal();
3551 Result += Val.toString(10);
3552 Result += ",\n";
3553 }
3554 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003555 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003556 }
3557 }
3558
3559 Result += "\t";
3560 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003561 return false;
3562}
3563
3564
3565/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3566/// It handles elaborated types, as well as enum types in the process.
3567void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3568 std::string &Result) {
3569 QualType Type = fieldDecl->getType();
3570 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003571
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003572 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3573 if (!EleboratedType)
3574 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003575 Result += Name;
3576 if (fieldDecl->isBitField()) {
3577 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3578 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003579 else if (EleboratedType && Type->isArrayType()) {
3580 CanQualType CType = Context->getCanonicalType(Type);
3581 while (isa<ArrayType>(CType)) {
3582 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3583 Result += "[";
3584 llvm::APInt Dim = CAT->getSize();
3585 Result += utostr(Dim.getZExtValue());
3586 Result += "]";
3587 }
3588 CType = CType->getAs<ArrayType>()->getElementType();
3589 }
3590 }
3591
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003592 Result += ";\n";
3593}
3594
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003595/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3596/// an objective-c class with ivars.
3597void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3598 std::string &Result) {
3599 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3600 assert(CDecl->getName() != "" &&
3601 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003602 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003603 SmallVector<ObjCIvarDecl *, 8> IVars;
3604 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003605 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003606 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003607
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003608 SourceLocation LocStart = CDecl->getLocStart();
3609 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003610
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003611 const char *startBuf = SM->getCharacterData(LocStart);
3612 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003613
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003614 // If no ivars and no root or if its root, directly or indirectly,
3615 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003616 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003617 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3618 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3619 ReplaceText(LocStart, endBuf-startBuf, Result);
3620 return;
3621 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003622
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003623 Result += "\nstruct ";
3624 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003625 Result += "_IMPL {\n";
3626
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003627 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003628 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3629 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3630 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003631 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003632 TagsDefinedInIvarDecls.clear();
3633 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3634 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003635
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003636 Result += "};\n";
3637 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3638 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003639 // Mark this struct as having been generated.
3640 if (!ObjCSynthesizedStructs.insert(CDecl))
3641 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003642}
3643
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003644static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3645 ObjCIvarDecl *IvarDecl, std::string &Result) {
3646 Result += "OBJC_IVAR_$_";
3647 Result += IDecl->getName();
3648 Result += "$";
3649 Result += IvarDecl->getName();
3650}
3651
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003652/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3653/// have been referenced in an ivar access expression.
3654void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3655 std::string &Result) {
3656 // write out ivar offset symbols which have been referenced in an ivar
3657 // access expression.
3658 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3659 if (Ivars.empty())
3660 return;
3661 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3662 e = Ivars.end(); i != e; i++) {
3663 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003664 Result += "\n";
3665 if (LangOpts.MicrosoftExt)
3666 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003667 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003668 if (LangOpts.MicrosoftExt &&
3669 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003670 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3671 Result += "__declspec(dllimport) ";
3672
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003673 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003674 WriteInternalIvarName(CDecl, IvarDecl, Result);
3675 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003676 }
3677}
3678
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003679//===----------------------------------------------------------------------===//
3680// Meta Data Emission
3681//===----------------------------------------------------------------------===//
3682
3683
3684/// RewriteImplementations - This routine rewrites all method implementations
3685/// and emits meta-data.
3686
3687void RewriteModernObjC::RewriteImplementations() {
3688 int ClsDefCount = ClassImplementation.size();
3689 int CatDefCount = CategoryImplementation.size();
3690
3691 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003692 for (int i = 0; i < ClsDefCount; i++) {
3693 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3694 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3695 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003696 assert(false &&
3697 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003698 RewriteImplementationDecl(OIMP);
3699 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003700
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003701 for (int i = 0; i < CatDefCount; i++) {
3702 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3703 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3704 if (CDecl->isImplicitInterfaceDecl())
3705 assert(false &&
3706 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003707 RewriteImplementationDecl(CIMP);
3708 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003709}
3710
3711void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3712 const std::string &Name,
3713 ValueDecl *VD, bool def) {
3714 assert(BlockByRefDeclNo.count(VD) &&
3715 "RewriteByRefString: ByRef decl missing");
3716 if (def)
3717 ResultStr += "struct ";
3718 ResultStr += "__Block_byref_" + Name +
3719 "_" + utostr(BlockByRefDeclNo[VD]) ;
3720}
3721
3722static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3723 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3724 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3725 return false;
3726}
3727
3728std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3729 StringRef funcName,
3730 std::string Tag) {
3731 const FunctionType *AFT = CE->getFunctionType();
3732 QualType RT = AFT->getResultType();
3733 std::string StructRef = "struct " + Tag;
3734 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003735 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003736
3737 BlockDecl *BD = CE->getBlockDecl();
3738
3739 if (isa<FunctionNoProtoType>(AFT)) {
3740 // No user-supplied arguments. Still need to pass in a pointer to the
3741 // block (to reference imported block decl refs).
3742 S += "(" + StructRef + " *__cself)";
3743 } else if (BD->param_empty()) {
3744 S += "(" + StructRef + " *__cself)";
3745 } else {
3746 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3747 assert(FT && "SynthesizeBlockFunc: No function proto");
3748 S += '(';
3749 // first add the implicit argument.
3750 S += StructRef + " *__cself, ";
3751 std::string ParamStr;
3752 for (BlockDecl::param_iterator AI = BD->param_begin(),
3753 E = BD->param_end(); AI != E; ++AI) {
3754 if (AI != BD->param_begin()) S += ", ";
3755 ParamStr = (*AI)->getNameAsString();
3756 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003757 (void)convertBlockPointerToFunctionPointer(QT);
3758 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003759 S += ParamStr;
3760 }
3761 if (FT->isVariadic()) {
3762 if (!BD->param_empty()) S += ", ";
3763 S += "...";
3764 }
3765 S += ')';
3766 }
3767 S += " {\n";
3768
3769 // Create local declarations to avoid rewriting all closure decl ref exprs.
3770 // First, emit a declaration for all "by ref" decls.
3771 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3772 E = BlockByRefDecls.end(); I != E; ++I) {
3773 S += " ";
3774 std::string Name = (*I)->getNameAsString();
3775 std::string TypeString;
3776 RewriteByRefString(TypeString, Name, (*I));
3777 TypeString += " *";
3778 Name = TypeString + Name;
3779 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3780 }
3781 // Next, emit a declaration for all "by copy" declarations.
3782 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3783 E = BlockByCopyDecls.end(); I != E; ++I) {
3784 S += " ";
3785 // Handle nested closure invocation. For example:
3786 //
3787 // void (^myImportedClosure)(void);
3788 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3789 //
3790 // void (^anotherClosure)(void);
3791 // anotherClosure = ^(void) {
3792 // myImportedClosure(); // import and invoke the closure
3793 // };
3794 //
3795 if (isTopLevelBlockPointerType((*I)->getType())) {
3796 RewriteBlockPointerTypeVariable(S, (*I));
3797 S += " = (";
3798 RewriteBlockPointerType(S, (*I)->getType());
3799 S += ")";
3800 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3801 }
3802 else {
3803 std::string Name = (*I)->getNameAsString();
3804 QualType QT = (*I)->getType();
3805 if (HasLocalVariableExternalStorage(*I))
3806 QT = Context->getPointerType(QT);
3807 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3808 S += Name + " = __cself->" +
3809 (*I)->getNameAsString() + "; // bound by copy\n";
3810 }
3811 }
3812 std::string RewrittenStr = RewrittenBlockExprs[CE];
3813 const char *cstr = RewrittenStr.c_str();
3814 while (*cstr++ != '{') ;
3815 S += cstr;
3816 S += "\n";
3817 return S;
3818}
3819
3820std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3821 StringRef funcName,
3822 std::string Tag) {
3823 std::string StructRef = "struct " + Tag;
3824 std::string S = "static void __";
3825
3826 S += funcName;
3827 S += "_block_copy_" + utostr(i);
3828 S += "(" + StructRef;
3829 S += "*dst, " + StructRef;
3830 S += "*src) {";
3831 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3832 E = ImportedBlockDecls.end(); I != E; ++I) {
3833 ValueDecl *VD = (*I);
3834 S += "_Block_object_assign((void*)&dst->";
3835 S += (*I)->getNameAsString();
3836 S += ", (void*)src->";
3837 S += (*I)->getNameAsString();
3838 if (BlockByRefDeclsPtrSet.count((*I)))
3839 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3840 else if (VD->getType()->isBlockPointerType())
3841 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3842 else
3843 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3844 }
3845 S += "}\n";
3846
3847 S += "\nstatic void __";
3848 S += funcName;
3849 S += "_block_dispose_" + utostr(i);
3850 S += "(" + StructRef;
3851 S += "*src) {";
3852 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3853 E = ImportedBlockDecls.end(); I != E; ++I) {
3854 ValueDecl *VD = (*I);
3855 S += "_Block_object_dispose((void*)src->";
3856 S += (*I)->getNameAsString();
3857 if (BlockByRefDeclsPtrSet.count((*I)))
3858 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3859 else if (VD->getType()->isBlockPointerType())
3860 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3861 else
3862 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3863 }
3864 S += "}\n";
3865 return S;
3866}
3867
3868std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3869 std::string Desc) {
3870 std::string S = "\nstruct " + Tag;
3871 std::string Constructor = " " + Tag;
3872
3873 S += " {\n struct __block_impl impl;\n";
3874 S += " struct " + Desc;
3875 S += "* Desc;\n";
3876
3877 Constructor += "(void *fp, "; // Invoke function pointer.
3878 Constructor += "struct " + Desc; // Descriptor pointer.
3879 Constructor += " *desc";
3880
3881 if (BlockDeclRefs.size()) {
3882 // Output all "by copy" declarations.
3883 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3884 E = BlockByCopyDecls.end(); I != E; ++I) {
3885 S += " ";
3886 std::string FieldName = (*I)->getNameAsString();
3887 std::string ArgName = "_" + FieldName;
3888 // Handle nested closure invocation. For example:
3889 //
3890 // void (^myImportedBlock)(void);
3891 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3892 //
3893 // void (^anotherBlock)(void);
3894 // anotherBlock = ^(void) {
3895 // myImportedBlock(); // import and invoke the closure
3896 // };
3897 //
3898 if (isTopLevelBlockPointerType((*I)->getType())) {
3899 S += "struct __block_impl *";
3900 Constructor += ", void *" + ArgName;
3901 } else {
3902 QualType QT = (*I)->getType();
3903 if (HasLocalVariableExternalStorage(*I))
3904 QT = Context->getPointerType(QT);
3905 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3906 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3907 Constructor += ", " + ArgName;
3908 }
3909 S += FieldName + ";\n";
3910 }
3911 // Output all "by ref" declarations.
3912 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3913 E = BlockByRefDecls.end(); I != E; ++I) {
3914 S += " ";
3915 std::string FieldName = (*I)->getNameAsString();
3916 std::string ArgName = "_" + FieldName;
3917 {
3918 std::string TypeString;
3919 RewriteByRefString(TypeString, FieldName, (*I));
3920 TypeString += " *";
3921 FieldName = TypeString + FieldName;
3922 ArgName = TypeString + ArgName;
3923 Constructor += ", " + ArgName;
3924 }
3925 S += FieldName + "; // by ref\n";
3926 }
3927 // Finish writing the constructor.
3928 Constructor += ", int flags=0)";
3929 // Initialize all "by copy" arguments.
3930 bool firsTime = true;
3931 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3932 E = BlockByCopyDecls.end(); I != E; ++I) {
3933 std::string Name = (*I)->getNameAsString();
3934 if (firsTime) {
3935 Constructor += " : ";
3936 firsTime = false;
3937 }
3938 else
3939 Constructor += ", ";
3940 if (isTopLevelBlockPointerType((*I)->getType()))
3941 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3942 else
3943 Constructor += Name + "(_" + Name + ")";
3944 }
3945 // Initialize all "by ref" arguments.
3946 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3947 E = BlockByRefDecls.end(); I != E; ++I) {
3948 std::string Name = (*I)->getNameAsString();
3949 if (firsTime) {
3950 Constructor += " : ";
3951 firsTime = false;
3952 }
3953 else
3954 Constructor += ", ";
3955 Constructor += Name + "(_" + Name + "->__forwarding)";
3956 }
3957
3958 Constructor += " {\n";
3959 if (GlobalVarDecl)
3960 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3961 else
3962 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3963 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3964
3965 Constructor += " Desc = desc;\n";
3966 } else {
3967 // Finish writing the constructor.
3968 Constructor += ", int flags=0) {\n";
3969 if (GlobalVarDecl)
3970 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3971 else
3972 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3973 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3974 Constructor += " Desc = desc;\n";
3975 }
3976 Constructor += " ";
3977 Constructor += "}\n";
3978 S += Constructor;
3979 S += "};\n";
3980 return S;
3981}
3982
3983std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3984 std::string ImplTag, int i,
3985 StringRef FunName,
3986 unsigned hasCopy) {
3987 std::string S = "\nstatic struct " + DescTag;
3988
3989 S += " {\n unsigned long reserved;\n";
3990 S += " unsigned long Block_size;\n";
3991 if (hasCopy) {
3992 S += " void (*copy)(struct ";
3993 S += ImplTag; S += "*, struct ";
3994 S += ImplTag; S += "*);\n";
3995
3996 S += " void (*dispose)(struct ";
3997 S += ImplTag; S += "*);\n";
3998 }
3999 S += "} ";
4000
4001 S += DescTag + "_DATA = { 0, sizeof(struct ";
4002 S += ImplTag + ")";
4003 if (hasCopy) {
4004 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4005 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4006 }
4007 S += "};\n";
4008 return S;
4009}
4010
4011void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4012 StringRef FunName) {
4013 // Insert declaration for the function in which block literal is used.
4014 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
4015 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4016 bool RewriteSC = (GlobalVarDecl &&
4017 !Blocks.empty() &&
4018 GlobalVarDecl->getStorageClass() == SC_Static &&
4019 GlobalVarDecl->getType().getCVRQualifiers());
4020 if (RewriteSC) {
4021 std::string SC(" void __");
4022 SC += GlobalVarDecl->getNameAsString();
4023 SC += "() {}";
4024 InsertText(FunLocStart, SC);
4025 }
4026
4027 // Insert closures that were part of the function.
4028 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4029 CollectBlockDeclRefInfo(Blocks[i]);
4030 // Need to copy-in the inner copied-in variables not actually used in this
4031 // block.
4032 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004033 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004034 ValueDecl *VD = Exp->getDecl();
4035 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004036 if (!VD->hasAttr<BlocksAttr>()) {
4037 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4038 BlockByCopyDeclsPtrSet.insert(VD);
4039 BlockByCopyDecls.push_back(VD);
4040 }
4041 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004042 }
John McCallf4b88a42012-03-10 09:33:50 +00004043
4044 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004045 BlockByRefDeclsPtrSet.insert(VD);
4046 BlockByRefDecls.push_back(VD);
4047 }
John McCallf4b88a42012-03-10 09:33:50 +00004048
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004049 // imported objects in the inner blocks not used in the outer
4050 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004051 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004052 VD->getType()->isBlockPointerType())
4053 ImportedBlockDecls.insert(VD);
4054 }
4055
4056 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4057 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4058
4059 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4060
4061 InsertText(FunLocStart, CI);
4062
4063 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4064
4065 InsertText(FunLocStart, CF);
4066
4067 if (ImportedBlockDecls.size()) {
4068 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4069 InsertText(FunLocStart, HF);
4070 }
4071 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4072 ImportedBlockDecls.size() > 0);
4073 InsertText(FunLocStart, BD);
4074
4075 BlockDeclRefs.clear();
4076 BlockByRefDecls.clear();
4077 BlockByRefDeclsPtrSet.clear();
4078 BlockByCopyDecls.clear();
4079 BlockByCopyDeclsPtrSet.clear();
4080 ImportedBlockDecls.clear();
4081 }
4082 if (RewriteSC) {
4083 // Must insert any 'const/volatile/static here. Since it has been
4084 // removed as result of rewriting of block literals.
4085 std::string SC;
4086 if (GlobalVarDecl->getStorageClass() == SC_Static)
4087 SC = "static ";
4088 if (GlobalVarDecl->getType().isConstQualified())
4089 SC += "const ";
4090 if (GlobalVarDecl->getType().isVolatileQualified())
4091 SC += "volatile ";
4092 if (GlobalVarDecl->getType().isRestrictQualified())
4093 SC += "restrict ";
4094 InsertText(FunLocStart, SC);
4095 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004096 if (GlobalConstructionExp) {
4097 // extra fancy dance for global literal expression.
4098
4099 // Always the latest block expression on the block stack.
4100 std::string Tag = "__";
4101 Tag += FunName;
4102 Tag += "_block_impl_";
4103 Tag += utostr(Blocks.size()-1);
4104 std::string globalBuf = "static ";
4105 globalBuf += Tag; globalBuf += " ";
4106 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004107
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004108 llvm::raw_string_ostream constructorExprBuf(SStr);
4109 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4110 PrintingPolicy(LangOpts));
4111 globalBuf += constructorExprBuf.str();
4112 globalBuf += ";\n";
4113 InsertText(FunLocStart, globalBuf);
4114 GlobalConstructionExp = 0;
4115 }
4116
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004117 Blocks.clear();
4118 InnerDeclRefsCount.clear();
4119 InnerDeclRefs.clear();
4120 RewrittenBlockExprs.clear();
4121}
4122
4123void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4124 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
4125 StringRef FuncName = FD->getName();
4126
4127 SynthesizeBlockLiterals(FunLocStart, FuncName);
4128}
4129
4130static void BuildUniqueMethodName(std::string &Name,
4131 ObjCMethodDecl *MD) {
4132 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4133 Name = IFace->getName();
4134 Name += "__" + MD->getSelector().getAsString();
4135 // Convert colons to underscores.
4136 std::string::size_type loc = 0;
4137 while ((loc = Name.find(":", loc)) != std::string::npos)
4138 Name.replace(loc, 1, "_");
4139}
4140
4141void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4142 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4143 //SourceLocation FunLocStart = MD->getLocStart();
4144 SourceLocation FunLocStart = MD->getLocStart();
4145 std::string FuncName;
4146 BuildUniqueMethodName(FuncName, MD);
4147 SynthesizeBlockLiterals(FunLocStart, FuncName);
4148}
4149
4150void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4151 for (Stmt::child_range CI = S->children(); CI; ++CI)
4152 if (*CI) {
4153 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4154 GetBlockDeclRefExprs(CBE->getBody());
4155 else
4156 GetBlockDeclRefExprs(*CI);
4157 }
4158 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004159 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4160 if (DRE->refersToEnclosingLocal() &&
4161 HasLocalVariableExternalStorage(DRE->getDecl())) {
4162 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004163 }
4164
4165 return;
4166}
4167
4168void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004169 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004170 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4171 for (Stmt::child_range CI = S->children(); CI; ++CI)
4172 if (*CI) {
4173 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4174 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4175 GetInnerBlockDeclRefExprs(CBE->getBody(),
4176 InnerBlockDeclRefs,
4177 InnerContexts);
4178 }
4179 else
4180 GetInnerBlockDeclRefExprs(*CI,
4181 InnerBlockDeclRefs,
4182 InnerContexts);
4183
4184 }
4185 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004186 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4187 if (DRE->refersToEnclosingLocal()) {
4188 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4189 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4190 InnerBlockDeclRefs.push_back(DRE);
4191 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4192 if (Var->isFunctionOrMethodVarDecl())
4193 ImportedLocalExternalDecls.insert(Var);
4194 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004195 }
4196
4197 return;
4198}
4199
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004200/// convertObjCTypeToCStyleType - This routine converts such objc types
4201/// as qualified objects, and blocks to their closest c/c++ types that
4202/// it can. It returns true if input type was modified.
4203bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4204 QualType oldT = T;
4205 convertBlockPointerToFunctionPointer(T);
4206 if (T->isFunctionPointerType()) {
4207 QualType PointeeTy;
4208 if (const PointerType* PT = T->getAs<PointerType>()) {
4209 PointeeTy = PT->getPointeeType();
4210 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4211 T = convertFunctionTypeOfBlocks(FT);
4212 T = Context->getPointerType(T);
4213 }
4214 }
4215 }
4216
4217 convertToUnqualifiedObjCType(T);
4218 return T != oldT;
4219}
4220
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004221/// convertFunctionTypeOfBlocks - This routine converts a function type
4222/// whose result type may be a block pointer or whose argument type(s)
4223/// might be block pointers to an equivalent function type replacing
4224/// all block pointers to function pointers.
4225QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4226 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4227 // FTP will be null for closures that don't take arguments.
4228 // Generate a funky cast.
4229 SmallVector<QualType, 8> ArgTypes;
4230 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004231 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004232
4233 if (FTP) {
4234 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4235 E = FTP->arg_type_end(); I && (I != E); ++I) {
4236 QualType t = *I;
4237 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004238 if (convertObjCTypeToCStyleType(t))
4239 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004240 ArgTypes.push_back(t);
4241 }
4242 }
4243 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004244 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004245 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4246 else FuncType = QualType(FT, 0);
4247 return FuncType;
4248}
4249
4250Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4251 // Navigate to relevant type information.
4252 const BlockPointerType *CPT = 0;
4253
4254 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4255 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004256 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4257 CPT = MExpr->getType()->getAs<BlockPointerType>();
4258 }
4259 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4260 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4261 }
4262 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4263 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4264 else if (const ConditionalOperator *CEXPR =
4265 dyn_cast<ConditionalOperator>(BlockExp)) {
4266 Expr *LHSExp = CEXPR->getLHS();
4267 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4268 Expr *RHSExp = CEXPR->getRHS();
4269 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4270 Expr *CONDExp = CEXPR->getCond();
4271 ConditionalOperator *CondExpr =
4272 new (Context) ConditionalOperator(CONDExp,
4273 SourceLocation(), cast<Expr>(LHSStmt),
4274 SourceLocation(), cast<Expr>(RHSStmt),
4275 Exp->getType(), VK_RValue, OK_Ordinary);
4276 return CondExpr;
4277 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4278 CPT = IRE->getType()->getAs<BlockPointerType>();
4279 } else if (const PseudoObjectExpr *POE
4280 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4281 CPT = POE->getType()->castAs<BlockPointerType>();
4282 } else {
4283 assert(1 && "RewriteBlockClass: Bad type");
4284 }
4285 assert(CPT && "RewriteBlockClass: Bad type");
4286 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4287 assert(FT && "RewriteBlockClass: Bad type");
4288 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4289 // FTP will be null for closures that don't take arguments.
4290
4291 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4292 SourceLocation(), SourceLocation(),
4293 &Context->Idents.get("__block_impl"));
4294 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4295
4296 // Generate a funky cast.
4297 SmallVector<QualType, 8> ArgTypes;
4298
4299 // Push the block argument type.
4300 ArgTypes.push_back(PtrBlock);
4301 if (FTP) {
4302 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4303 E = FTP->arg_type_end(); I && (I != E); ++I) {
4304 QualType t = *I;
4305 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4306 if (!convertBlockPointerToFunctionPointer(t))
4307 convertToUnqualifiedObjCType(t);
4308 ArgTypes.push_back(t);
4309 }
4310 }
4311 // Now do the pointer to function cast.
4312 QualType PtrToFuncCastType
4313 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4314
4315 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4316
4317 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4318 CK_BitCast,
4319 const_cast<Expr*>(BlockExp));
4320 // Don't forget the parens to enforce the proper binding.
4321 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4322 BlkCast);
4323 //PE->dump();
4324
4325 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4326 SourceLocation(),
4327 &Context->Idents.get("FuncPtr"),
4328 Context->VoidPtrTy, 0,
4329 /*BitWidth=*/0, /*Mutable=*/true,
4330 /*HasInit=*/false);
4331 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4332 FD->getType(), VK_LValue,
4333 OK_Ordinary);
4334
4335
4336 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4337 CK_BitCast, ME);
4338 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4339
4340 SmallVector<Expr*, 8> BlkExprs;
4341 // Add the implicit argument.
4342 BlkExprs.push_back(BlkCast);
4343 // Add the user arguments.
4344 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4345 E = Exp->arg_end(); I != E; ++I) {
4346 BlkExprs.push_back(*I);
4347 }
4348 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4349 BlkExprs.size(),
4350 Exp->getType(), VK_RValue,
4351 SourceLocation());
4352 return CE;
4353}
4354
4355// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004356// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004357// For example:
4358//
4359// int main() {
4360// __block Foo *f;
4361// __block int i;
4362//
4363// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004364// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004365// i = 77;
4366// };
4367//}
John McCallf4b88a42012-03-10 09:33:50 +00004368Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004369 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4370 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004371 ValueDecl *VD = DeclRefExp->getDecl();
4372 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004373
4374 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4375 SourceLocation(),
4376 &Context->Idents.get("__forwarding"),
4377 Context->VoidPtrTy, 0,
4378 /*BitWidth=*/0, /*Mutable=*/true,
4379 /*HasInit=*/false);
4380 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4381 FD, SourceLocation(),
4382 FD->getType(), VK_LValue,
4383 OK_Ordinary);
4384
4385 StringRef Name = VD->getName();
4386 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4387 &Context->Idents.get(Name),
4388 Context->VoidPtrTy, 0,
4389 /*BitWidth=*/0, /*Mutable=*/true,
4390 /*HasInit=*/false);
4391 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4392 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4393
4394
4395
4396 // Need parens to enforce precedence.
4397 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4398 DeclRefExp->getExprLoc(),
4399 ME);
4400 ReplaceStmt(DeclRefExp, PE);
4401 return PE;
4402}
4403
4404// Rewrites the imported local variable V with external storage
4405// (static, extern, etc.) as *V
4406//
4407Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4408 ValueDecl *VD = DRE->getDecl();
4409 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4410 if (!ImportedLocalExternalDecls.count(Var))
4411 return DRE;
4412 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4413 VK_LValue, OK_Ordinary,
4414 DRE->getLocation());
4415 // Need parens to enforce precedence.
4416 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4417 Exp);
4418 ReplaceStmt(DRE, PE);
4419 return PE;
4420}
4421
4422void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4423 SourceLocation LocStart = CE->getLParenLoc();
4424 SourceLocation LocEnd = CE->getRParenLoc();
4425
4426 // Need to avoid trying to rewrite synthesized casts.
4427 if (LocStart.isInvalid())
4428 return;
4429 // Need to avoid trying to rewrite casts contained in macros.
4430 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4431 return;
4432
4433 const char *startBuf = SM->getCharacterData(LocStart);
4434 const char *endBuf = SM->getCharacterData(LocEnd);
4435 QualType QT = CE->getType();
4436 const Type* TypePtr = QT->getAs<Type>();
4437 if (isa<TypeOfExprType>(TypePtr)) {
4438 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4439 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4440 std::string TypeAsString = "(";
4441 RewriteBlockPointerType(TypeAsString, QT);
4442 TypeAsString += ")";
4443 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4444 return;
4445 }
4446 // advance the location to startArgList.
4447 const char *argPtr = startBuf;
4448
4449 while (*argPtr++ && (argPtr < endBuf)) {
4450 switch (*argPtr) {
4451 case '^':
4452 // Replace the '^' with '*'.
4453 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4454 ReplaceText(LocStart, 1, "*");
4455 break;
4456 }
4457 }
4458 return;
4459}
4460
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004461void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4462 CastKind CastKind = IC->getCastKind();
4463
4464 if (CastKind == CK_BlockPointerToObjCPointerCast) {
4465 CStyleCastExpr * CastExpr =
4466 NoTypeInfoCStyleCastExpr(Context, IC->getType(), CK_BitCast, IC);
4467 ReplaceStmt(IC, CastExpr);
4468 }
4469 else if (CastKind == CK_AnyPointerToBlockPointerCast) {
4470 QualType BlockT = IC->getType();
4471 (void)convertBlockPointerToFunctionPointer(BlockT);
4472 CStyleCastExpr * CastExpr =
4473 NoTypeInfoCStyleCastExpr(Context, BlockT, CK_BitCast, IC);
4474 ReplaceStmt(IC, CastExpr);
4475 }
4476 return;
4477}
4478
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004479void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4480 SourceLocation DeclLoc = FD->getLocation();
4481 unsigned parenCount = 0;
4482
4483 // We have 1 or more arguments that have closure pointers.
4484 const char *startBuf = SM->getCharacterData(DeclLoc);
4485 const char *startArgList = strchr(startBuf, '(');
4486
4487 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4488
4489 parenCount++;
4490 // advance the location to startArgList.
4491 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4492 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4493
4494 const char *argPtr = startArgList;
4495
4496 while (*argPtr++ && parenCount) {
4497 switch (*argPtr) {
4498 case '^':
4499 // Replace the '^' with '*'.
4500 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4501 ReplaceText(DeclLoc, 1, "*");
4502 break;
4503 case '(':
4504 parenCount++;
4505 break;
4506 case ')':
4507 parenCount--;
4508 break;
4509 }
4510 }
4511 return;
4512}
4513
4514bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4515 const FunctionProtoType *FTP;
4516 const PointerType *PT = QT->getAs<PointerType>();
4517 if (PT) {
4518 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4519 } else {
4520 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4521 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4522 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4523 }
4524 if (FTP) {
4525 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4526 E = FTP->arg_type_end(); I != E; ++I)
4527 if (isTopLevelBlockPointerType(*I))
4528 return true;
4529 }
4530 return false;
4531}
4532
4533bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4534 const FunctionProtoType *FTP;
4535 const PointerType *PT = QT->getAs<PointerType>();
4536 if (PT) {
4537 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4538 } else {
4539 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4540 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4541 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4542 }
4543 if (FTP) {
4544 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4545 E = FTP->arg_type_end(); I != E; ++I) {
4546 if ((*I)->isObjCQualifiedIdType())
4547 return true;
4548 if ((*I)->isObjCObjectPointerType() &&
4549 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4550 return true;
4551 }
4552
4553 }
4554 return false;
4555}
4556
4557void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4558 const char *&RParen) {
4559 const char *argPtr = strchr(Name, '(');
4560 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4561
4562 LParen = argPtr; // output the start.
4563 argPtr++; // skip past the left paren.
4564 unsigned parenCount = 1;
4565
4566 while (*argPtr && parenCount) {
4567 switch (*argPtr) {
4568 case '(': parenCount++; break;
4569 case ')': parenCount--; break;
4570 default: break;
4571 }
4572 if (parenCount) argPtr++;
4573 }
4574 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4575 RParen = argPtr; // output the end
4576}
4577
4578void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4579 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4580 RewriteBlockPointerFunctionArgs(FD);
4581 return;
4582 }
4583 // Handle Variables and Typedefs.
4584 SourceLocation DeclLoc = ND->getLocation();
4585 QualType DeclT;
4586 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4587 DeclT = VD->getType();
4588 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4589 DeclT = TDD->getUnderlyingType();
4590 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4591 DeclT = FD->getType();
4592 else
4593 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4594
4595 const char *startBuf = SM->getCharacterData(DeclLoc);
4596 const char *endBuf = startBuf;
4597 // scan backward (from the decl location) for the end of the previous decl.
4598 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4599 startBuf--;
4600 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4601 std::string buf;
4602 unsigned OrigLength=0;
4603 // *startBuf != '^' if we are dealing with a pointer to function that
4604 // may take block argument types (which will be handled below).
4605 if (*startBuf == '^') {
4606 // Replace the '^' with '*', computing a negative offset.
4607 buf = '*';
4608 startBuf++;
4609 OrigLength++;
4610 }
4611 while (*startBuf != ')') {
4612 buf += *startBuf;
4613 startBuf++;
4614 OrigLength++;
4615 }
4616 buf += ')';
4617 OrigLength++;
4618
4619 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4620 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4621 // Replace the '^' with '*' for arguments.
4622 // Replace id<P> with id/*<>*/
4623 DeclLoc = ND->getLocation();
4624 startBuf = SM->getCharacterData(DeclLoc);
4625 const char *argListBegin, *argListEnd;
4626 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4627 while (argListBegin < argListEnd) {
4628 if (*argListBegin == '^')
4629 buf += '*';
4630 else if (*argListBegin == '<') {
4631 buf += "/*";
4632 buf += *argListBegin++;
4633 OrigLength++;;
4634 while (*argListBegin != '>') {
4635 buf += *argListBegin++;
4636 OrigLength++;
4637 }
4638 buf += *argListBegin;
4639 buf += "*/";
4640 }
4641 else
4642 buf += *argListBegin;
4643 argListBegin++;
4644 OrigLength++;
4645 }
4646 buf += ')';
4647 OrigLength++;
4648 }
4649 ReplaceText(Start, OrigLength, buf);
4650
4651 return;
4652}
4653
4654
4655/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4656/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4657/// struct Block_byref_id_object *src) {
4658/// _Block_object_assign (&_dest->object, _src->object,
4659/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4660/// [|BLOCK_FIELD_IS_WEAK]) // object
4661/// _Block_object_assign(&_dest->object, _src->object,
4662/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4663/// [|BLOCK_FIELD_IS_WEAK]) // block
4664/// }
4665/// And:
4666/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4667/// _Block_object_dispose(_src->object,
4668/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4669/// [|BLOCK_FIELD_IS_WEAK]) // object
4670/// _Block_object_dispose(_src->object,
4671/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4672/// [|BLOCK_FIELD_IS_WEAK]) // block
4673/// }
4674
4675std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4676 int flag) {
4677 std::string S;
4678 if (CopyDestroyCache.count(flag))
4679 return S;
4680 CopyDestroyCache.insert(flag);
4681 S = "static void __Block_byref_id_object_copy_";
4682 S += utostr(flag);
4683 S += "(void *dst, void *src) {\n";
4684
4685 // offset into the object pointer is computed as:
4686 // void * + void* + int + int + void* + void *
4687 unsigned IntSize =
4688 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4689 unsigned VoidPtrSize =
4690 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4691
4692 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4693 S += " _Block_object_assign((char*)dst + ";
4694 S += utostr(offset);
4695 S += ", *(void * *) ((char*)src + ";
4696 S += utostr(offset);
4697 S += "), ";
4698 S += utostr(flag);
4699 S += ");\n}\n";
4700
4701 S += "static void __Block_byref_id_object_dispose_";
4702 S += utostr(flag);
4703 S += "(void *src) {\n";
4704 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4705 S += utostr(offset);
4706 S += "), ";
4707 S += utostr(flag);
4708 S += ");\n}\n";
4709 return S;
4710}
4711
4712/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4713/// the declaration into:
4714/// struct __Block_byref_ND {
4715/// void *__isa; // NULL for everything except __weak pointers
4716/// struct __Block_byref_ND *__forwarding;
4717/// int32_t __flags;
4718/// int32_t __size;
4719/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4720/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4721/// typex ND;
4722/// };
4723///
4724/// It then replaces declaration of ND variable with:
4725/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4726/// __size=sizeof(struct __Block_byref_ND),
4727/// ND=initializer-if-any};
4728///
4729///
4730void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4731 // Insert declaration for the function in which block literal is
4732 // used.
4733 if (CurFunctionDeclToDeclareForBlock)
4734 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4735 int flag = 0;
4736 int isa = 0;
4737 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4738 if (DeclLoc.isInvalid())
4739 // If type location is missing, it is because of missing type (a warning).
4740 // Use variable's location which is good for this case.
4741 DeclLoc = ND->getLocation();
4742 const char *startBuf = SM->getCharacterData(DeclLoc);
4743 SourceLocation X = ND->getLocEnd();
4744 X = SM->getExpansionLoc(X);
4745 const char *endBuf = SM->getCharacterData(X);
4746 std::string Name(ND->getNameAsString());
4747 std::string ByrefType;
4748 RewriteByRefString(ByrefType, Name, ND, true);
4749 ByrefType += " {\n";
4750 ByrefType += " void *__isa;\n";
4751 RewriteByRefString(ByrefType, Name, ND);
4752 ByrefType += " *__forwarding;\n";
4753 ByrefType += " int __flags;\n";
4754 ByrefType += " int __size;\n";
4755 // Add void *__Block_byref_id_object_copy;
4756 // void *__Block_byref_id_object_dispose; if needed.
4757 QualType Ty = ND->getType();
4758 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4759 if (HasCopyAndDispose) {
4760 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4761 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4762 }
4763
4764 QualType T = Ty;
4765 (void)convertBlockPointerToFunctionPointer(T);
4766 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4767
4768 ByrefType += " " + Name + ";\n";
4769 ByrefType += "};\n";
4770 // Insert this type in global scope. It is needed by helper function.
4771 SourceLocation FunLocStart;
4772 if (CurFunctionDef)
4773 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4774 else {
4775 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4776 FunLocStart = CurMethodDef->getLocStart();
4777 }
4778 InsertText(FunLocStart, ByrefType);
4779 if (Ty.isObjCGCWeak()) {
4780 flag |= BLOCK_FIELD_IS_WEAK;
4781 isa = 1;
4782 }
4783
4784 if (HasCopyAndDispose) {
4785 flag = BLOCK_BYREF_CALLER;
4786 QualType Ty = ND->getType();
4787 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4788 if (Ty->isBlockPointerType())
4789 flag |= BLOCK_FIELD_IS_BLOCK;
4790 else
4791 flag |= BLOCK_FIELD_IS_OBJECT;
4792 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4793 if (!HF.empty())
4794 InsertText(FunLocStart, HF);
4795 }
4796
4797 // struct __Block_byref_ND ND =
4798 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4799 // initializer-if-any};
4800 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004801 // FIXME. rewriter does not support __block c++ objects which
4802 // require construction.
4803 if (hasInit && dyn_cast<CXXConstructExpr>(ND->getInit()))
4804 hasInit = false;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004805 unsigned flags = 0;
4806 if (HasCopyAndDispose)
4807 flags |= BLOCK_HAS_COPY_DISPOSE;
4808 Name = ND->getNameAsString();
4809 ByrefType.clear();
4810 RewriteByRefString(ByrefType, Name, ND);
4811 std::string ForwardingCastType("(");
4812 ForwardingCastType += ByrefType + " *)";
4813 if (!hasInit) {
4814 ByrefType += " " + Name + " = {(void*)";
4815 ByrefType += utostr(isa);
4816 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4817 ByrefType += utostr(flags);
4818 ByrefType += ", ";
4819 ByrefType += "sizeof(";
4820 RewriteByRefString(ByrefType, Name, ND);
4821 ByrefType += ")";
4822 if (HasCopyAndDispose) {
4823 ByrefType += ", __Block_byref_id_object_copy_";
4824 ByrefType += utostr(flag);
4825 ByrefType += ", __Block_byref_id_object_dispose_";
4826 ByrefType += utostr(flag);
4827 }
4828 ByrefType += "};\n";
4829 unsigned nameSize = Name.size();
4830 // for block or function pointer declaration. Name is aleady
4831 // part of the declaration.
4832 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4833 nameSize = 1;
4834 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4835 }
4836 else {
4837 SourceLocation startLoc;
4838 Expr *E = ND->getInit();
4839 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4840 startLoc = ECE->getLParenLoc();
4841 else
4842 startLoc = E->getLocStart();
4843 startLoc = SM->getExpansionLoc(startLoc);
4844 endBuf = SM->getCharacterData(startLoc);
4845 ByrefType += " " + Name;
4846 ByrefType += " = {(void*)";
4847 ByrefType += utostr(isa);
4848 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4849 ByrefType += utostr(flags);
4850 ByrefType += ", ";
4851 ByrefType += "sizeof(";
4852 RewriteByRefString(ByrefType, Name, ND);
4853 ByrefType += "), ";
4854 if (HasCopyAndDispose) {
4855 ByrefType += "__Block_byref_id_object_copy_";
4856 ByrefType += utostr(flag);
4857 ByrefType += ", __Block_byref_id_object_dispose_";
4858 ByrefType += utostr(flag);
4859 ByrefType += ", ";
4860 }
4861 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4862
4863 // Complete the newly synthesized compound expression by inserting a right
4864 // curly brace before the end of the declaration.
4865 // FIXME: This approach avoids rewriting the initializer expression. It
4866 // also assumes there is only one declarator. For example, the following
4867 // isn't currently supported by this routine (in general):
4868 //
4869 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4870 //
4871 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4872 const char *semiBuf = strchr(startInitializerBuf, ';');
4873 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4874 SourceLocation semiLoc =
4875 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4876
4877 InsertText(semiLoc, "}");
4878 }
4879 return;
4880}
4881
4882void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4883 // Add initializers for any closure decl refs.
4884 GetBlockDeclRefExprs(Exp->getBody());
4885 if (BlockDeclRefs.size()) {
4886 // Unique all "by copy" declarations.
4887 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004888 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004889 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4890 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4891 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4892 }
4893 }
4894 // Unique all "by ref" declarations.
4895 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004896 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004897 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4898 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4899 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4900 }
4901 }
4902 // Find any imported blocks...they will need special attention.
4903 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004904 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004905 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4906 BlockDeclRefs[i]->getType()->isBlockPointerType())
4907 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4908 }
4909}
4910
4911FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4912 IdentifierInfo *ID = &Context->Idents.get(name);
4913 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4914 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4915 SourceLocation(), ID, FType, 0, SC_Extern,
4916 SC_None, false, false);
4917}
4918
4919Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004920 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004921
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004922 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004923
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004924 Blocks.push_back(Exp);
4925
4926 CollectBlockDeclRefInfo(Exp);
4927
4928 // Add inner imported variables now used in current block.
4929 int countOfInnerDecls = 0;
4930 if (!InnerBlockDeclRefs.empty()) {
4931 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004932 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004933 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004934 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004935 // We need to save the copied-in variables in nested
4936 // blocks because it is needed at the end for some of the API generations.
4937 // See SynthesizeBlockLiterals routine.
4938 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4939 BlockDeclRefs.push_back(Exp);
4940 BlockByCopyDeclsPtrSet.insert(VD);
4941 BlockByCopyDecls.push_back(VD);
4942 }
John McCallf4b88a42012-03-10 09:33:50 +00004943 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004944 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4945 BlockDeclRefs.push_back(Exp);
4946 BlockByRefDeclsPtrSet.insert(VD);
4947 BlockByRefDecls.push_back(VD);
4948 }
4949 }
4950 // Find any imported blocks...they will need special attention.
4951 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004952 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004953 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4954 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4955 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4956 }
4957 InnerDeclRefsCount.push_back(countOfInnerDecls);
4958
4959 std::string FuncName;
4960
4961 if (CurFunctionDef)
4962 FuncName = CurFunctionDef->getNameAsString();
4963 else if (CurMethodDef)
4964 BuildUniqueMethodName(FuncName, CurMethodDef);
4965 else if (GlobalVarDecl)
4966 FuncName = std::string(GlobalVarDecl->getNameAsString());
4967
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004968 bool GlobalBlockExpr =
4969 block->getDeclContext()->getRedeclContext()->isFileContext();
4970
4971 if (GlobalBlockExpr && !GlobalVarDecl) {
4972 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4973 GlobalBlockExpr = false;
4974 }
4975
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004976 std::string BlockNumber = utostr(Blocks.size()-1);
4977
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004978 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4979
4980 // Get a pointer to the function type so we can cast appropriately.
4981 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4982 QualType FType = Context->getPointerType(BFT);
4983
4984 FunctionDecl *FD;
4985 Expr *NewRep;
4986
4987 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004988 std::string Tag;
4989
4990 if (GlobalBlockExpr)
4991 Tag = "__global_";
4992 else
4993 Tag = "__";
4994 Tag += FuncName + "_block_impl_" + BlockNumber;
4995
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004996 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004997 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004998 SourceLocation());
4999
5000 SmallVector<Expr*, 4> InitExprs;
5001
5002 // Initialize the block function.
5003 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005004 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5005 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005006 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5007 CK_BitCast, Arg);
5008 InitExprs.push_back(castExpr);
5009
5010 // Initialize the block descriptor.
5011 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5012
5013 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5014 SourceLocation(), SourceLocation(),
5015 &Context->Idents.get(DescData.c_str()),
5016 Context->VoidPtrTy, 0,
5017 SC_Static, SC_None);
5018 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005019 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005020 Context->VoidPtrTy,
5021 VK_LValue,
5022 SourceLocation()),
5023 UO_AddrOf,
5024 Context->getPointerType(Context->VoidPtrTy),
5025 VK_RValue, OK_Ordinary,
5026 SourceLocation());
5027 InitExprs.push_back(DescRefExpr);
5028
5029 // Add initializers for any closure decl refs.
5030 if (BlockDeclRefs.size()) {
5031 Expr *Exp;
5032 // Output all "by copy" declarations.
5033 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5034 E = BlockByCopyDecls.end(); I != E; ++I) {
5035 if (isObjCType((*I)->getType())) {
5036 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5037 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005038 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5039 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005040 if (HasLocalVariableExternalStorage(*I)) {
5041 QualType QT = (*I)->getType();
5042 QT = Context->getPointerType(QT);
5043 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5044 OK_Ordinary, SourceLocation());
5045 }
5046 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5047 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005048 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5049 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005050 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5051 CK_BitCast, Arg);
5052 } else {
5053 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005054 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5055 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005056 if (HasLocalVariableExternalStorage(*I)) {
5057 QualType QT = (*I)->getType();
5058 QT = Context->getPointerType(QT);
5059 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5060 OK_Ordinary, SourceLocation());
5061 }
5062
5063 }
5064 InitExprs.push_back(Exp);
5065 }
5066 // Output all "by ref" declarations.
5067 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5068 E = BlockByRefDecls.end(); I != E; ++I) {
5069 ValueDecl *ND = (*I);
5070 std::string Name(ND->getNameAsString());
5071 std::string RecName;
5072 RewriteByRefString(RecName, Name, ND, true);
5073 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5074 + sizeof("struct"));
5075 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5076 SourceLocation(), SourceLocation(),
5077 II);
5078 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5079 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5080
5081 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005082 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005083 SourceLocation());
5084 bool isNestedCapturedVar = false;
5085 if (block)
5086 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5087 ce = block->capture_end(); ci != ce; ++ci) {
5088 const VarDecl *variable = ci->getVariable();
5089 if (variable == ND && ci->isNested()) {
5090 assert (ci->isByRef() &&
5091 "SynthBlockInitExpr - captured block variable is not byref");
5092 isNestedCapturedVar = true;
5093 break;
5094 }
5095 }
5096 // captured nested byref variable has its address passed. Do not take
5097 // its address again.
5098 if (!isNestedCapturedVar)
5099 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5100 Context->getPointerType(Exp->getType()),
5101 VK_RValue, OK_Ordinary, SourceLocation());
5102 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5103 InitExprs.push_back(Exp);
5104 }
5105 }
5106 if (ImportedBlockDecls.size()) {
5107 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5108 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5109 unsigned IntSize =
5110 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5111 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5112 Context->IntTy, SourceLocation());
5113 InitExprs.push_back(FlagExp);
5114 }
5115 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5116 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005117
5118 if (GlobalBlockExpr) {
5119 assert (GlobalConstructionExp == 0 &&
5120 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5121 GlobalConstructionExp = NewRep;
5122 NewRep = DRE;
5123 }
5124
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005125 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5126 Context->getPointerType(NewRep->getType()),
5127 VK_RValue, OK_Ordinary, SourceLocation());
5128 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5129 NewRep);
5130 BlockDeclRefs.clear();
5131 BlockByRefDecls.clear();
5132 BlockByRefDeclsPtrSet.clear();
5133 BlockByCopyDecls.clear();
5134 BlockByCopyDeclsPtrSet.clear();
5135 ImportedBlockDecls.clear();
5136 return NewRep;
5137}
5138
5139bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5140 if (const ObjCForCollectionStmt * CS =
5141 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5142 return CS->getElement() == DS;
5143 return false;
5144}
5145
5146//===----------------------------------------------------------------------===//
5147// Function Body / Expression rewriting
5148//===----------------------------------------------------------------------===//
5149
5150Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5151 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5152 isa<DoStmt>(S) || isa<ForStmt>(S))
5153 Stmts.push_back(S);
5154 else if (isa<ObjCForCollectionStmt>(S)) {
5155 Stmts.push_back(S);
5156 ObjCBcLabelNo.push_back(++BcLabelCount);
5157 }
5158
5159 // Pseudo-object operations and ivar references need special
5160 // treatment because we're going to recursively rewrite them.
5161 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5162 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5163 return RewritePropertyOrImplicitSetter(PseudoOp);
5164 } else {
5165 return RewritePropertyOrImplicitGetter(PseudoOp);
5166 }
5167 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5168 return RewriteObjCIvarRefExpr(IvarRefExpr);
5169 }
5170
5171 SourceRange OrigStmtRange = S->getSourceRange();
5172
5173 // Perform a bottom up rewrite of all children.
5174 for (Stmt::child_range CI = S->children(); CI; ++CI)
5175 if (*CI) {
5176 Stmt *childStmt = (*CI);
5177 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5178 if (newStmt) {
5179 *CI = newStmt;
5180 }
5181 }
5182
5183 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005184 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005185 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5186 InnerContexts.insert(BE->getBlockDecl());
5187 ImportedLocalExternalDecls.clear();
5188 GetInnerBlockDeclRefExprs(BE->getBody(),
5189 InnerBlockDeclRefs, InnerContexts);
5190 // Rewrite the block body in place.
5191 Stmt *SaveCurrentBody = CurrentBody;
5192 CurrentBody = BE->getBody();
5193 PropParentMap = 0;
5194 // block literal on rhs of a property-dot-sytax assignment
5195 // must be replaced by its synthesize ast so getRewrittenText
5196 // works as expected. In this case, what actually ends up on RHS
5197 // is the blockTranscribed which is the helper function for the
5198 // block literal; as in: self.c = ^() {[ace ARR];};
5199 bool saveDisableReplaceStmt = DisableReplaceStmt;
5200 DisableReplaceStmt = false;
5201 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5202 DisableReplaceStmt = saveDisableReplaceStmt;
5203 CurrentBody = SaveCurrentBody;
5204 PropParentMap = 0;
5205 ImportedLocalExternalDecls.clear();
5206 // Now we snarf the rewritten text and stash it away for later use.
5207 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5208 RewrittenBlockExprs[BE] = Str;
5209
5210 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5211
5212 //blockTranscribed->dump();
5213 ReplaceStmt(S, blockTranscribed);
5214 return blockTranscribed;
5215 }
5216 // Handle specific things.
5217 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5218 return RewriteAtEncode(AtEncode);
5219
5220 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5221 return RewriteAtSelector(AtSelector);
5222
5223 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5224 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005225
5226 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5227 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005228
5229 if (ObjCNumericLiteral *NumericLitExpr = dyn_cast<ObjCNumericLiteral>(S))
5230 return RewriteObjCNumericLiteralExpr(NumericLitExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005231
5232 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5233 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005234
5235 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5236 dyn_cast<ObjCDictionaryLiteral>(S))
5237 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005238
5239 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5240#if 0
5241 // Before we rewrite it, put the original message expression in a comment.
5242 SourceLocation startLoc = MessExpr->getLocStart();
5243 SourceLocation endLoc = MessExpr->getLocEnd();
5244
5245 const char *startBuf = SM->getCharacterData(startLoc);
5246 const char *endBuf = SM->getCharacterData(endLoc);
5247
5248 std::string messString;
5249 messString += "// ";
5250 messString.append(startBuf, endBuf-startBuf+1);
5251 messString += "\n";
5252
5253 // FIXME: Missing definition of
5254 // InsertText(clang::SourceLocation, char const*, unsigned int).
5255 // InsertText(startLoc, messString.c_str(), messString.size());
5256 // Tried this, but it didn't work either...
5257 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5258#endif
5259 return RewriteMessageExpr(MessExpr);
5260 }
5261
5262 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5263 return RewriteObjCTryStmt(StmtTry);
5264
5265 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5266 return RewriteObjCSynchronizedStmt(StmtTry);
5267
5268 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5269 return RewriteObjCThrowStmt(StmtThrow);
5270
5271 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5272 return RewriteObjCProtocolExpr(ProtocolExp);
5273
5274 if (ObjCForCollectionStmt *StmtForCollection =
5275 dyn_cast<ObjCForCollectionStmt>(S))
5276 return RewriteObjCForCollectionStmt(StmtForCollection,
5277 OrigStmtRange.getEnd());
5278 if (BreakStmt *StmtBreakStmt =
5279 dyn_cast<BreakStmt>(S))
5280 return RewriteBreakStmt(StmtBreakStmt);
5281 if (ContinueStmt *StmtContinueStmt =
5282 dyn_cast<ContinueStmt>(S))
5283 return RewriteContinueStmt(StmtContinueStmt);
5284
5285 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5286 // and cast exprs.
5287 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5288 // FIXME: What we're doing here is modifying the type-specifier that
5289 // precedes the first Decl. In the future the DeclGroup should have
5290 // a separate type-specifier that we can rewrite.
5291 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5292 // the context of an ObjCForCollectionStmt. For example:
5293 // NSArray *someArray;
5294 // for (id <FooProtocol> index in someArray) ;
5295 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5296 // and it depends on the original text locations/positions.
5297 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5298 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5299
5300 // Blocks rewrite rules.
5301 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5302 DI != DE; ++DI) {
5303 Decl *SD = *DI;
5304 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5305 if (isTopLevelBlockPointerType(ND->getType()))
5306 RewriteBlockPointerDecl(ND);
5307 else if (ND->getType()->isFunctionPointerType())
5308 CheckFunctionPointerDecl(ND->getType(), ND);
5309 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5310 if (VD->hasAttr<BlocksAttr>()) {
5311 static unsigned uniqueByrefDeclCount = 0;
5312 assert(!BlockByRefDeclNo.count(ND) &&
5313 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5314 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5315 RewriteByRefVar(VD);
5316 }
5317 else
5318 RewriteTypeOfDecl(VD);
5319 }
5320 }
5321 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5322 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5323 RewriteBlockPointerDecl(TD);
5324 else if (TD->getUnderlyingType()->isFunctionPointerType())
5325 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5326 }
5327 }
5328 }
5329
5330 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5331 RewriteObjCQualifiedInterfaceTypes(CE);
5332
5333 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5334 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5335 assert(!Stmts.empty() && "Statement stack is empty");
5336 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5337 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5338 && "Statement stack mismatch");
5339 Stmts.pop_back();
5340 }
5341 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005342 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5343 ValueDecl *VD = DRE->getDecl();
5344 if (VD->hasAttr<BlocksAttr>())
5345 return RewriteBlockDeclRefExpr(DRE);
5346 if (HasLocalVariableExternalStorage(VD))
5347 return RewriteLocalVariableExternalStorage(DRE);
5348 }
5349
5350 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5351 if (CE->getCallee()->getType()->isBlockPointerType()) {
5352 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5353 ReplaceStmt(S, BlockCall);
5354 return BlockCall;
5355 }
5356 }
5357 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5358 RewriteCastExpr(CE);
5359 }
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005360#if 0
5361 // FIXME. Cannot safely rewrite ImplicitCasts. This is the 2nd failed
5362 // attempt: (id)((__typeof(z))_Block_copy((const void *)(z)));
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005363 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5364 RewriteImplicitCastObjCExpr(ICE);
5365 }
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005366
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005367 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5368 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5369 ICE->getSubExpr(),
5370 SourceLocation());
5371 // Get the new text.
5372 std::string SStr;
5373 llvm::raw_string_ostream Buf(SStr);
5374 Replacement->printPretty(Buf, *Context);
5375 const std::string &Str = Buf.str();
5376
5377 printf("CAST = %s\n", &Str[0]);
5378 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5379 delete S;
5380 return Replacement;
5381 }
5382#endif
5383 // Return this stmt unmodified.
5384 return S;
5385}
5386
5387void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5388 for (RecordDecl::field_iterator i = RD->field_begin(),
5389 e = RD->field_end(); i != e; ++i) {
5390 FieldDecl *FD = *i;
5391 if (isTopLevelBlockPointerType(FD->getType()))
5392 RewriteBlockPointerDecl(FD);
5393 if (FD->getType()->isObjCQualifiedIdType() ||
5394 FD->getType()->isObjCQualifiedInterfaceType())
5395 RewriteObjCQualifiedInterfaceTypes(FD);
5396 }
5397}
5398
5399/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5400/// main file of the input.
5401void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5402 switch (D->getKind()) {
5403 case Decl::Function: {
5404 FunctionDecl *FD = cast<FunctionDecl>(D);
5405 if (FD->isOverloadedOperator())
5406 return;
5407
5408 // Since function prototypes don't have ParmDecl's, we check the function
5409 // prototype. This enables us to rewrite function declarations and
5410 // definitions using the same code.
5411 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5412
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005413 if (!FD->isThisDeclarationADefinition())
5414 break;
5415
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005416 // FIXME: If this should support Obj-C++, support CXXTryStmt
5417 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5418 CurFunctionDef = FD;
5419 CurFunctionDeclToDeclareForBlock = FD;
5420 CurrentBody = Body;
5421 Body =
5422 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5423 FD->setBody(Body);
5424 CurrentBody = 0;
5425 if (PropParentMap) {
5426 delete PropParentMap;
5427 PropParentMap = 0;
5428 }
5429 // This synthesizes and inserts the block "impl" struct, invoke function,
5430 // and any copy/dispose helper functions.
5431 InsertBlockLiteralsWithinFunction(FD);
5432 CurFunctionDef = 0;
5433 CurFunctionDeclToDeclareForBlock = 0;
5434 }
5435 break;
5436 }
5437 case Decl::ObjCMethod: {
5438 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5439 if (CompoundStmt *Body = MD->getCompoundBody()) {
5440 CurMethodDef = MD;
5441 CurrentBody = Body;
5442 Body =
5443 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5444 MD->setBody(Body);
5445 CurrentBody = 0;
5446 if (PropParentMap) {
5447 delete PropParentMap;
5448 PropParentMap = 0;
5449 }
5450 InsertBlockLiteralsWithinMethod(MD);
5451 CurMethodDef = 0;
5452 }
5453 break;
5454 }
5455 case Decl::ObjCImplementation: {
5456 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5457 ClassImplementation.push_back(CI);
5458 break;
5459 }
5460 case Decl::ObjCCategoryImpl: {
5461 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5462 CategoryImplementation.push_back(CI);
5463 break;
5464 }
5465 case Decl::Var: {
5466 VarDecl *VD = cast<VarDecl>(D);
5467 RewriteObjCQualifiedInterfaceTypes(VD);
5468 if (isTopLevelBlockPointerType(VD->getType()))
5469 RewriteBlockPointerDecl(VD);
5470 else if (VD->getType()->isFunctionPointerType()) {
5471 CheckFunctionPointerDecl(VD->getType(), VD);
5472 if (VD->getInit()) {
5473 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5474 RewriteCastExpr(CE);
5475 }
5476 }
5477 } else if (VD->getType()->isRecordType()) {
5478 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5479 if (RD->isCompleteDefinition())
5480 RewriteRecordBody(RD);
5481 }
5482 if (VD->getInit()) {
5483 GlobalVarDecl = VD;
5484 CurrentBody = VD->getInit();
5485 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5486 CurrentBody = 0;
5487 if (PropParentMap) {
5488 delete PropParentMap;
5489 PropParentMap = 0;
5490 }
5491 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5492 GlobalVarDecl = 0;
5493
5494 // This is needed for blocks.
5495 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5496 RewriteCastExpr(CE);
5497 }
5498 }
5499 break;
5500 }
5501 case Decl::TypeAlias:
5502 case Decl::Typedef: {
5503 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5504 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5505 RewriteBlockPointerDecl(TD);
5506 else if (TD->getUnderlyingType()->isFunctionPointerType())
5507 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5508 }
5509 break;
5510 }
5511 case Decl::CXXRecord:
5512 case Decl::Record: {
5513 RecordDecl *RD = cast<RecordDecl>(D);
5514 if (RD->isCompleteDefinition())
5515 RewriteRecordBody(RD);
5516 break;
5517 }
5518 default:
5519 break;
5520 }
5521 // Nothing yet.
5522}
5523
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005524/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5525/// protocol reference symbols in the for of:
5526/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5527static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5528 ObjCProtocolDecl *PDecl,
5529 std::string &Result) {
5530 // Also output .objc_protorefs$B section and its meta-data.
5531 if (Context->getLangOpts().MicrosoftExt)
5532 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5533 Result += "struct _protocol_t *";
5534 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5535 Result += PDecl->getNameAsString();
5536 Result += " = &";
5537 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5538 Result += ";\n";
5539}
5540
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005541void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5542 if (Diags.hasErrorOccurred())
5543 return;
5544
5545 RewriteInclude();
5546
5547 // Here's a great place to add any extra declarations that may be needed.
5548 // Write out meta data for each @protocol(<expr>).
5549 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005550 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005551 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005552 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5553 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005554
5555 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005556 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5557 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5558 // Write struct declaration for the class matching its ivar declarations.
5559 // Note that for modern abi, this is postponed until the end of TU
5560 // because class extensions and the implementation might declare their own
5561 // private ivars.
5562 RewriteInterfaceDecl(CDecl);
5563 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005564
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005565 if (ClassImplementation.size() || CategoryImplementation.size())
5566 RewriteImplementations();
5567
5568 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5569 // we are done.
5570 if (const RewriteBuffer *RewriteBuf =
5571 Rewrite.getRewriteBufferFor(MainFileID)) {
5572 //printf("Changed:\n");
5573 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5574 } else {
5575 llvm::errs() << "No changes\n";
5576 }
5577
5578 if (ClassImplementation.size() || CategoryImplementation.size() ||
5579 ProtocolExprDecls.size()) {
5580 // Rewrite Objective-c meta data*
5581 std::string ResultStr;
5582 RewriteMetaDataIntoBuffer(ResultStr);
5583 // Emit metadata.
5584 *OutFile << ResultStr;
5585 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005586 // Emit ImageInfo;
5587 {
5588 std::string ResultStr;
5589 WriteImageInfo(ResultStr);
5590 *OutFile << ResultStr;
5591 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005592 OutFile->flush();
5593}
5594
5595void RewriteModernObjC::Initialize(ASTContext &context) {
5596 InitializeCommon(context);
5597
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005598 Preamble += "#ifndef __OBJC2__\n";
5599 Preamble += "#define __OBJC2__\n";
5600 Preamble += "#endif\n";
5601
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005602 // declaring objc_selector outside the parameter list removes a silly
5603 // scope related warning...
5604 if (IsHeader)
5605 Preamble = "#pragma once\n";
5606 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005607 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5608 Preamble += "\n\tstruct objc_object *superClass; ";
5609 // Add a constructor for creating temporary objects.
5610 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5611 Preamble += ": object(o), superClass(s) {} ";
5612 Preamble += "\n};\n";
5613
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005614 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005615 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005616 // These are currently generated.
5617 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005618 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005619 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005620 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5621 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005622 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005623 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005624 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005625 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5626 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005627 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005628
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005629 // These need be generated for performance. Currently they are not,
5630 // using API calls instead.
5631 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5632 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5633 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5634
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005635 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005636 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5637 Preamble += "typedef struct objc_object Protocol;\n";
5638 Preamble += "#define _REWRITER_typedef_Protocol\n";
5639 Preamble += "#endif\n";
5640 if (LangOpts.MicrosoftExt) {
5641 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5642 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005643 }
5644 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005645 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005646
5647 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5648 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5649 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5650 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5651 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5652
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005653 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5654 Preamble += "(const char *);\n";
5655 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5656 Preamble += "(struct objc_class *);\n";
5657 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5658 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005659 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005660 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005661 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5662 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005663 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5664 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5665 Preamble += "struct __objcFastEnumerationState {\n\t";
5666 Preamble += "unsigned long state;\n\t";
5667 Preamble += "void **itemsPtr;\n\t";
5668 Preamble += "unsigned long *mutationsPtr;\n\t";
5669 Preamble += "unsigned long extra[5];\n};\n";
5670 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5671 Preamble += "#define __FASTENUMERATIONSTATE\n";
5672 Preamble += "#endif\n";
5673 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5674 Preamble += "struct __NSConstantStringImpl {\n";
5675 Preamble += " int *isa;\n";
5676 Preamble += " int flags;\n";
5677 Preamble += " char *str;\n";
5678 Preamble += " long length;\n";
5679 Preamble += "};\n";
5680 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5681 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5682 Preamble += "#else\n";
5683 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5684 Preamble += "#endif\n";
5685 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5686 Preamble += "#endif\n";
5687 // Blocks preamble.
5688 Preamble += "#ifndef BLOCK_IMPL\n";
5689 Preamble += "#define BLOCK_IMPL\n";
5690 Preamble += "struct __block_impl {\n";
5691 Preamble += " void *isa;\n";
5692 Preamble += " int Flags;\n";
5693 Preamble += " int Reserved;\n";
5694 Preamble += " void *FuncPtr;\n";
5695 Preamble += "};\n";
5696 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5697 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5698 Preamble += "extern \"C\" __declspec(dllexport) "
5699 "void _Block_object_assign(void *, const void *, const int);\n";
5700 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5701 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5702 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5703 Preamble += "#else\n";
5704 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5705 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5706 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5707 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5708 Preamble += "#endif\n";
5709 Preamble += "#endif\n";
5710 if (LangOpts.MicrosoftExt) {
5711 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5712 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5713 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5714 Preamble += "#define __attribute__(X)\n";
5715 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005716 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005717 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005718 Preamble += "#endif\n";
5719 Preamble += "#ifndef __block\n";
5720 Preamble += "#define __block\n";
5721 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005722 }
5723 else {
5724 Preamble += "#define __block\n";
5725 Preamble += "#define __weak\n";
5726 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005727
5728 // Declarations required for modern objective-c array and dictionary literals.
5729 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005730 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005731 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005732 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005733 Preamble += "\tva_list marker;\n";
5734 Preamble += "\tva_start(marker, count);\n";
5735 Preamble += "\tarr = new void *[count];\n";
5736 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5737 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5738 Preamble += "\tva_end( marker );\n";
5739 Preamble += " };\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005740 Preamble += " __NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005741 Preamble += "\tdelete[] arr;\n";
5742 Preamble += " }\n";
5743 Preamble += "};\n";
5744
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005745 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5746 // as this avoids warning in any 64bit/32bit compilation model.
5747 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5748}
5749
5750/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5751/// ivar offset.
5752void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5753 std::string &Result) {
5754 if (ivar->isBitField()) {
5755 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5756 // place all bitfields at offset 0.
5757 Result += "0";
5758 } else {
5759 Result += "__OFFSETOFIVAR__(struct ";
5760 Result += ivar->getContainingInterface()->getNameAsString();
5761 if (LangOpts.MicrosoftExt)
5762 Result += "_IMPL";
5763 Result += ", ";
5764 Result += ivar->getNameAsString();
5765 Result += ")";
5766 }
5767}
5768
5769/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5770/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005771/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005772/// char *attributes;
5773/// }
5774
5775/// struct _prop_list_t {
5776/// uint32_t entsize; // sizeof(struct _prop_t)
5777/// uint32_t count_of_properties;
5778/// struct _prop_t prop_list[count_of_properties];
5779/// }
5780
5781/// struct _protocol_t;
5782
5783/// struct _protocol_list_t {
5784/// long protocol_count; // Note, this is 32/64 bit
5785/// struct _protocol_t * protocol_list[protocol_count];
5786/// }
5787
5788/// struct _objc_method {
5789/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005790/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005791/// char *_imp;
5792/// }
5793
5794/// struct _method_list_t {
5795/// uint32_t entsize; // sizeof(struct _objc_method)
5796/// uint32_t method_count;
5797/// struct _objc_method method_list[method_count];
5798/// }
5799
5800/// struct _protocol_t {
5801/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005802/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005803/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005804/// const struct method_list_t *instance_methods;
5805/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005806/// const struct method_list_t *optionalInstanceMethods;
5807/// const struct method_list_t *optionalClassMethods;
5808/// const struct _prop_list_t * properties;
5809/// const uint32_t size; // sizeof(struct _protocol_t)
5810/// const uint32_t flags; // = 0
5811/// const char ** extendedMethodTypes;
5812/// }
5813
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005814/// struct _ivar_t {
5815/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005816/// const char *name;
5817/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005818/// uint32_t alignment;
5819/// uint32_t size;
5820/// }
5821
5822/// struct _ivar_list_t {
5823/// uint32 entsize; // sizeof(struct _ivar_t)
5824/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005825/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005826/// }
5827
5828/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005829/// uint32_t flags;
5830/// uint32_t instanceStart;
5831/// uint32_t instanceSize;
5832/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005833/// const uint8_t *ivarLayout;
5834/// const char *name;
5835/// const struct _method_list_t *baseMethods;
5836/// const struct _protocol_list_t *baseProtocols;
5837/// const struct _ivar_list_t *ivars;
5838/// const uint8_t *weakIvarLayout;
5839/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005840/// }
5841
5842/// struct _class_t {
5843/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005844/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005845/// void *cache;
5846/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005847/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005848/// }
5849
5850/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005851/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005852/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005853/// const struct _method_list_t *instance_methods;
5854/// const struct _method_list_t *class_methods;
5855/// const struct _protocol_list_t *protocols;
5856/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005857/// }
5858
5859/// MessageRefTy - LLVM for:
5860/// struct _message_ref_t {
5861/// IMP messenger;
5862/// SEL name;
5863/// };
5864
5865/// SuperMessageRefTy - LLVM for:
5866/// struct _super_message_ref_t {
5867/// SUPER_IMP messenger;
5868/// SEL name;
5869/// };
5870
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005871static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005872 static bool meta_data_declared = false;
5873 if (meta_data_declared)
5874 return;
5875
5876 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005877 Result += "\tconst char *name;\n";
5878 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005879 Result += "};\n";
5880
5881 Result += "\nstruct _protocol_t;\n";
5882
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005883 Result += "\nstruct _objc_method {\n";
5884 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005885 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005886 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005887 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005888
5889 Result += "\nstruct _protocol_t {\n";
5890 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005891 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005892 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005893 Result += "\tconst struct method_list_t *instance_methods;\n";
5894 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005895 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5896 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5897 Result += "\tconst struct _prop_list_t * properties;\n";
5898 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5899 Result += "\tconst unsigned int flags; // = 0\n";
5900 Result += "\tconst char ** extendedMethodTypes;\n";
5901 Result += "};\n";
5902
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005903 Result += "\nstruct _ivar_t {\n";
5904 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005905 Result += "\tconst char *name;\n";
5906 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005907 Result += "\tunsigned int alignment;\n";
5908 Result += "\tunsigned int size;\n";
5909 Result += "};\n";
5910
5911 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005912 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005913 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005914 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005915 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5916 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005917 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005918 Result += "\tconst unsigned char *ivarLayout;\n";
5919 Result += "\tconst char *name;\n";
5920 Result += "\tconst struct _method_list_t *baseMethods;\n";
5921 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5922 Result += "\tconst struct _ivar_list_t *ivars;\n";
5923 Result += "\tconst unsigned char *weakIvarLayout;\n";
5924 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005925 Result += "};\n";
5926
5927 Result += "\nstruct _class_t {\n";
5928 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005929 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005930 Result += "\tvoid *cache;\n";
5931 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005932 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005933 Result += "};\n";
5934
5935 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005936 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005937 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005938 Result += "\tconst struct _method_list_t *instance_methods;\n";
5939 Result += "\tconst struct _method_list_t *class_methods;\n";
5940 Result += "\tconst struct _protocol_list_t *protocols;\n";
5941 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005942 Result += "};\n";
5943
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005944 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005945 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005946 meta_data_declared = true;
5947}
5948
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005949static void Write_protocol_list_t_TypeDecl(std::string &Result,
5950 long super_protocol_count) {
5951 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5952 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5953 Result += "\tstruct _protocol_t *super_protocols[";
5954 Result += utostr(super_protocol_count); Result += "];\n";
5955 Result += "}";
5956}
5957
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005958static void Write_method_list_t_TypeDecl(std::string &Result,
5959 unsigned int method_count) {
5960 Result += "struct /*_method_list_t*/"; Result += " {\n";
5961 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5962 Result += "\tunsigned int method_count;\n";
5963 Result += "\tstruct _objc_method method_list[";
5964 Result += utostr(method_count); Result += "];\n";
5965 Result += "}";
5966}
5967
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005968static void Write__prop_list_t_TypeDecl(std::string &Result,
5969 unsigned int property_count) {
5970 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5971 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5972 Result += "\tunsigned int count_of_properties;\n";
5973 Result += "\tstruct _prop_t prop_list[";
5974 Result += utostr(property_count); Result += "];\n";
5975 Result += "}";
5976}
5977
Fariborz Jahanianae932952012-02-10 20:47:10 +00005978static void Write__ivar_list_t_TypeDecl(std::string &Result,
5979 unsigned int ivar_count) {
5980 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5981 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5982 Result += "\tunsigned int count;\n";
5983 Result += "\tstruct _ivar_t ivar_list[";
5984 Result += utostr(ivar_count); Result += "];\n";
5985 Result += "}";
5986}
5987
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005988static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5989 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5990 StringRef VarName,
5991 StringRef ProtocolName) {
5992 if (SuperProtocols.size() > 0) {
5993 Result += "\nstatic ";
5994 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5995 Result += " "; Result += VarName;
5996 Result += ProtocolName;
5997 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5998 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5999 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6000 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6001 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6002 Result += SuperPD->getNameAsString();
6003 if (i == e-1)
6004 Result += "\n};\n";
6005 else
6006 Result += ",\n";
6007 }
6008 }
6009}
6010
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006011static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6012 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006013 ArrayRef<ObjCMethodDecl *> Methods,
6014 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006015 StringRef TopLevelDeclName,
6016 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006017 if (Methods.size() > 0) {
6018 Result += "\nstatic ";
6019 Write_method_list_t_TypeDecl(Result, Methods.size());
6020 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006021 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006022 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6023 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6024 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6025 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6026 ObjCMethodDecl *MD = Methods[i];
6027 if (i == 0)
6028 Result += "\t{{(struct objc_selector *)\"";
6029 else
6030 Result += "\t{(struct objc_selector *)\"";
6031 Result += (MD)->getSelector().getAsString(); Result += "\"";
6032 Result += ", ";
6033 std::string MethodTypeString;
6034 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6035 Result += "\""; Result += MethodTypeString; Result += "\"";
6036 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006037 if (!MethodImpl)
6038 Result += "0";
6039 else {
6040 Result += "(void *)";
6041 Result += RewriteObj.MethodInternalNames[MD];
6042 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006043 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006044 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006045 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006046 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006047 }
6048 Result += "};\n";
6049 }
6050}
6051
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006052static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006053 ASTContext *Context, std::string &Result,
6054 ArrayRef<ObjCPropertyDecl *> Properties,
6055 const Decl *Container,
6056 StringRef VarName,
6057 StringRef ProtocolName) {
6058 if (Properties.size() > 0) {
6059 Result += "\nstatic ";
6060 Write__prop_list_t_TypeDecl(Result, Properties.size());
6061 Result += " "; Result += VarName;
6062 Result += ProtocolName;
6063 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6064 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6065 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6066 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6067 ObjCPropertyDecl *PropDecl = Properties[i];
6068 if (i == 0)
6069 Result += "\t{{\"";
6070 else
6071 Result += "\t{\"";
6072 Result += PropDecl->getName(); Result += "\",";
6073 std::string PropertyTypeString, QuotePropertyTypeString;
6074 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6075 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6076 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6077 if (i == e-1)
6078 Result += "}}\n";
6079 else
6080 Result += "},\n";
6081 }
6082 Result += "};\n";
6083 }
6084}
6085
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006086// Metadata flags
6087enum MetaDataDlags {
6088 CLS = 0x0,
6089 CLS_META = 0x1,
6090 CLS_ROOT = 0x2,
6091 OBJC2_CLS_HIDDEN = 0x10,
6092 CLS_EXCEPTION = 0x20,
6093
6094 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6095 CLS_HAS_IVAR_RELEASER = 0x40,
6096 /// class was compiled with -fobjc-arr
6097 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6098};
6099
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006100static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6101 unsigned int flags,
6102 const std::string &InstanceStart,
6103 const std::string &InstanceSize,
6104 ArrayRef<ObjCMethodDecl *>baseMethods,
6105 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6106 ArrayRef<ObjCIvarDecl *>ivars,
6107 ArrayRef<ObjCPropertyDecl *>Properties,
6108 StringRef VarName,
6109 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006110 Result += "\nstatic struct _class_ro_t ";
6111 Result += VarName; Result += ClassName;
6112 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6113 Result += "\t";
6114 Result += llvm::utostr(flags); Result += ", ";
6115 Result += InstanceStart; Result += ", ";
6116 Result += InstanceSize; Result += ", \n";
6117 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006118 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6119 if (Triple.getArch() == llvm::Triple::x86_64)
6120 // uint32_t const reserved; // only when building for 64bit targets
6121 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006122 // const uint8_t * const ivarLayout;
6123 Result += "0, \n\t";
6124 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006125 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006126 if (baseMethods.size() > 0) {
6127 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006128 if (metaclass)
6129 Result += "_OBJC_$_CLASS_METHODS_";
6130 else
6131 Result += "_OBJC_$_INSTANCE_METHODS_";
6132 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006133 Result += ",\n\t";
6134 }
6135 else
6136 Result += "0, \n\t";
6137
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006138 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006139 Result += "(const struct _objc_protocol_list *)&";
6140 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6141 Result += ",\n\t";
6142 }
6143 else
6144 Result += "0, \n\t";
6145
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006146 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006147 Result += "(const struct _ivar_list_t *)&";
6148 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6149 Result += ",\n\t";
6150 }
6151 else
6152 Result += "0, \n\t";
6153
6154 // weakIvarLayout
6155 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006156 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006157 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006158 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006159 Result += ",\n";
6160 }
6161 else
6162 Result += "0, \n";
6163
6164 Result += "};\n";
6165}
6166
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006167static void Write_class_t(ASTContext *Context, std::string &Result,
6168 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006169 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6170 bool rootClass = (!CDecl->getSuperClass());
6171 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006172
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006173 if (!rootClass) {
6174 // Find the Root class
6175 RootClass = CDecl->getSuperClass();
6176 while (RootClass->getSuperClass()) {
6177 RootClass = RootClass->getSuperClass();
6178 }
6179 }
6180
6181 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006182 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006183 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006184 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006185 if (CDecl->getImplementation())
6186 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006187 else
6188 Result += "__declspec(dllimport) ";
6189
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006190 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006191 Result += CDecl->getNameAsString();
6192 Result += ";\n";
6193 }
6194 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006195 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006196 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006197 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006198 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006199 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006200 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006201 else
6202 Result += "__declspec(dllimport) ";
6203
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006204 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006205 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006206 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006207 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006208
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006209 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006210 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006211 if (RootClass->getImplementation())
6212 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006213 else
6214 Result += "__declspec(dllimport) ";
6215
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006216 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006217 Result += VarName;
6218 Result += RootClass->getNameAsString();
6219 Result += ";\n";
6220 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006221 }
6222
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006223 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6224 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006225 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6226 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006227 if (metaclass) {
6228 if (!rootClass) {
6229 Result += "0, // &"; Result += VarName;
6230 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006231 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006232 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006233 Result += CDecl->getSuperClass()->getNameAsString();
6234 Result += ",\n\t";
6235 }
6236 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006237 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006238 Result += CDecl->getNameAsString();
6239 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006240 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006241 Result += ",\n\t";
6242 }
6243 }
6244 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006245 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006246 Result += CDecl->getNameAsString();
6247 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006248 if (!rootClass) {
6249 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006250 Result += CDecl->getSuperClass()->getNameAsString();
6251 Result += ",\n\t";
6252 }
6253 else
6254 Result += "0,\n\t";
6255 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006256 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6257 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6258 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006259 Result += "&_OBJC_METACLASS_RO_$_";
6260 else
6261 Result += "&_OBJC_CLASS_RO_$_";
6262 Result += CDecl->getNameAsString();
6263 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006264
6265 // Add static function to initialize some of the meta-data fields.
6266 // avoid doing it twice.
6267 if (metaclass)
6268 return;
6269
6270 const ObjCInterfaceDecl *SuperClass =
6271 rootClass ? CDecl : CDecl->getSuperClass();
6272
6273 Result += "static void OBJC_CLASS_SETUP_$_";
6274 Result += CDecl->getNameAsString();
6275 Result += "(void ) {\n";
6276 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6277 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006278 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006279
6280 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006281 Result += ".superclass = ";
6282 if (rootClass)
6283 Result += "&OBJC_CLASS_$_";
6284 else
6285 Result += "&OBJC_METACLASS_$_";
6286
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006287 Result += SuperClass->getNameAsString(); Result += ";\n";
6288
6289 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6290 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6291
6292 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6293 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6294 Result += CDecl->getNameAsString(); Result += ";\n";
6295
6296 if (!rootClass) {
6297 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6298 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6299 Result += SuperClass->getNameAsString(); Result += ";\n";
6300 }
6301
6302 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6303 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6304 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006305}
6306
Fariborz Jahanian61186122012-02-17 18:40:41 +00006307static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6308 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006309 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006310 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006311 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6312 ArrayRef<ObjCMethodDecl *> ClassMethods,
6313 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6314 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006315 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006316 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006317 // must declare an extern class object in case this class is not implemented
6318 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006319 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006320 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006321 if (ClassDecl->getImplementation())
6322 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006323 else
6324 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006325
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006326 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006327 Result += "OBJC_CLASS_$_"; Result += ClassName;
6328 Result += ";\n";
6329
Fariborz Jahanian61186122012-02-17 18:40:41 +00006330 Result += "\nstatic struct _category_t ";
6331 Result += "_OBJC_$_CATEGORY_";
6332 Result += ClassName; Result += "_$_"; Result += CatName;
6333 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6334 Result += "{\n";
6335 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006336 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006337 Result += ",\n";
6338 if (InstanceMethods.size() > 0) {
6339 Result += "\t(const struct _method_list_t *)&";
6340 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6341 Result += ClassName; Result += "_$_"; Result += CatName;
6342 Result += ",\n";
6343 }
6344 else
6345 Result += "\t0,\n";
6346
6347 if (ClassMethods.size() > 0) {
6348 Result += "\t(const struct _method_list_t *)&";
6349 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6350 Result += ClassName; Result += "_$_"; Result += CatName;
6351 Result += ",\n";
6352 }
6353 else
6354 Result += "\t0,\n";
6355
6356 if (RefedProtocols.size() > 0) {
6357 Result += "\t(const struct _protocol_list_t *)&";
6358 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6359 Result += ClassName; Result += "_$_"; Result += CatName;
6360 Result += ",\n";
6361 }
6362 else
6363 Result += "\t0,\n";
6364
6365 if (ClassProperties.size() > 0) {
6366 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6367 Result += ClassName; Result += "_$_"; Result += CatName;
6368 Result += ",\n";
6369 }
6370 else
6371 Result += "\t0,\n";
6372
6373 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006374
6375 // Add static function to initialize the class pointer in the category structure.
6376 Result += "static void OBJC_CATEGORY_SETUP_$_";
6377 Result += ClassDecl->getNameAsString();
6378 Result += "_$_";
6379 Result += CatName;
6380 Result += "(void ) {\n";
6381 Result += "\t_OBJC_$_CATEGORY_";
6382 Result += ClassDecl->getNameAsString();
6383 Result += "_$_";
6384 Result += CatName;
6385 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6386 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006387}
6388
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006389static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6390 ASTContext *Context, std::string &Result,
6391 ArrayRef<ObjCMethodDecl *> Methods,
6392 StringRef VarName,
6393 StringRef ProtocolName) {
6394 if (Methods.size() == 0)
6395 return;
6396
6397 Result += "\nstatic const char *";
6398 Result += VarName; Result += ProtocolName;
6399 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6400 Result += "{\n";
6401 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6402 ObjCMethodDecl *MD = Methods[i];
6403 std::string MethodTypeString, QuoteMethodTypeString;
6404 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6405 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6406 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6407 if (i == e-1)
6408 Result += "\n};\n";
6409 else {
6410 Result += ",\n";
6411 }
6412 }
6413}
6414
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006415static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6416 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006417 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006418 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006419 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006420 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6421 // this is what happens:
6422 /**
6423 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6424 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6425 Class->getVisibility() == HiddenVisibility)
6426 Visibility shoud be: HiddenVisibility;
6427 else
6428 Visibility shoud be: DefaultVisibility;
6429 */
6430
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006431 Result += "\n";
6432 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6433 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006434 if (Context->getLangOpts().MicrosoftExt)
6435 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6436
6437 if (!Context->getLangOpts().MicrosoftExt ||
6438 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006439 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006440 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006441 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006442 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006443 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006444 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6445 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006446 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6447 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006448 }
6449}
6450
Fariborz Jahanianae932952012-02-10 20:47:10 +00006451static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6452 ASTContext *Context, std::string &Result,
6453 ArrayRef<ObjCIvarDecl *> Ivars,
6454 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006455 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006456 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006457 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006458
Fariborz Jahanianae932952012-02-10 20:47:10 +00006459 Result += "\nstatic ";
6460 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6461 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006462 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006463 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6464 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6465 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6466 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6467 ObjCIvarDecl *IvarDecl = Ivars[i];
6468 if (i == 0)
6469 Result += "\t{{";
6470 else
6471 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006472 Result += "(unsigned long int *)&";
6473 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006474 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006475
6476 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6477 std::string IvarTypeString, QuoteIvarTypeString;
6478 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6479 IvarDecl);
6480 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6481 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6482
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006483 // FIXME. this alignment represents the host alignment and need be changed to
6484 // represent the target alignment.
6485 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6486 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006487 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006488 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6489 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006490 if (i == e-1)
6491 Result += "}}\n";
6492 else
6493 Result += "},\n";
6494 }
6495 Result += "};\n";
6496 }
6497}
6498
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006499/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006500void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6501 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006502
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006503 // Do not synthesize the protocol more than once.
6504 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6505 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006506 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006507
6508 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6509 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006510 // Must write out all protocol definitions in current qualifier list,
6511 // and in their nested qualifiers before writing out current definition.
6512 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6513 E = PDecl->protocol_end(); I != E; ++I)
6514 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006515
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006516 // Construct method lists.
6517 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6518 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6519 for (ObjCProtocolDecl::instmeth_iterator
6520 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6521 I != E; ++I) {
6522 ObjCMethodDecl *MD = *I;
6523 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6524 OptInstanceMethods.push_back(MD);
6525 } else {
6526 InstanceMethods.push_back(MD);
6527 }
6528 }
6529
6530 for (ObjCProtocolDecl::classmeth_iterator
6531 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6532 I != E; ++I) {
6533 ObjCMethodDecl *MD = *I;
6534 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6535 OptClassMethods.push_back(MD);
6536 } else {
6537 ClassMethods.push_back(MD);
6538 }
6539 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006540 std::vector<ObjCMethodDecl *> AllMethods;
6541 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6542 AllMethods.push_back(InstanceMethods[i]);
6543 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6544 AllMethods.push_back(ClassMethods[i]);
6545 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6546 AllMethods.push_back(OptInstanceMethods[i]);
6547 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6548 AllMethods.push_back(OptClassMethods[i]);
6549
6550 Write__extendedMethodTypes_initializer(*this, Context, Result,
6551 AllMethods,
6552 "_OBJC_PROTOCOL_METHOD_TYPES_",
6553 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006554 // Protocol's super protocol list
6555 std::vector<ObjCProtocolDecl *> SuperProtocols;
6556 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6557 E = PDecl->protocol_end(); I != E; ++I)
6558 SuperProtocols.push_back(*I);
6559
6560 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6561 "_OBJC_PROTOCOL_REFS_",
6562 PDecl->getNameAsString());
6563
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006564 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006565 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006566 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006567
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006568 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006569 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006570 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006571
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006572 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006573 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006574 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006575
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006576 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006577 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006578 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006579
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006580 // Protocol's property metadata.
6581 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6582 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6583 E = PDecl->prop_end(); I != E; ++I)
6584 ProtocolProperties.push_back(*I);
6585
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006586 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006587 /* Container */0,
6588 "_OBJC_PROTOCOL_PROPERTIES_",
6589 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006590
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006591 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006592 Result += "\n";
6593 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006594 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006595 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006596 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006597 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6598 Result += "\t0,\n"; // id is; is null
6599 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006600 if (SuperProtocols.size() > 0) {
6601 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6602 Result += PDecl->getNameAsString(); Result += ",\n";
6603 }
6604 else
6605 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006606 if (InstanceMethods.size() > 0) {
6607 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6608 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006609 }
6610 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006611 Result += "\t0,\n";
6612
6613 if (ClassMethods.size() > 0) {
6614 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6615 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006616 }
6617 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006618 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006619
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006620 if (OptInstanceMethods.size() > 0) {
6621 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6622 Result += PDecl->getNameAsString(); Result += ",\n";
6623 }
6624 else
6625 Result += "\t0,\n";
6626
6627 if (OptClassMethods.size() > 0) {
6628 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6629 Result += PDecl->getNameAsString(); Result += ",\n";
6630 }
6631 else
6632 Result += "\t0,\n";
6633
6634 if (ProtocolProperties.size() > 0) {
6635 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6636 Result += PDecl->getNameAsString(); Result += ",\n";
6637 }
6638 else
6639 Result += "\t0,\n";
6640
6641 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6642 Result += "\t0,\n";
6643
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006644 if (AllMethods.size() > 0) {
6645 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6646 Result += PDecl->getNameAsString();
6647 Result += "\n};\n";
6648 }
6649 else
6650 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006651
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006652 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006653 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006654 Result += "struct _protocol_t *";
6655 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6656 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6657 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006658
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006659 // Mark this protocol as having been generated.
6660 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6661 llvm_unreachable("protocol already synthesized");
6662
6663}
6664
6665void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6666 const ObjCList<ObjCProtocolDecl> &Protocols,
6667 StringRef prefix, StringRef ClassName,
6668 std::string &Result) {
6669 if (Protocols.empty()) return;
6670
6671 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006672 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006673
6674 // Output the top lovel protocol meta-data for the class.
6675 /* struct _objc_protocol_list {
6676 struct _objc_protocol_list *next;
6677 int protocol_count;
6678 struct _objc_protocol *class_protocols[];
6679 }
6680 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006681 Result += "\n";
6682 if (LangOpts.MicrosoftExt)
6683 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6684 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006685 Result += "\tstruct _objc_protocol_list *next;\n";
6686 Result += "\tint protocol_count;\n";
6687 Result += "\tstruct _objc_protocol *class_protocols[";
6688 Result += utostr(Protocols.size());
6689 Result += "];\n} _OBJC_";
6690 Result += prefix;
6691 Result += "_PROTOCOLS_";
6692 Result += ClassName;
6693 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6694 "{\n\t0, ";
6695 Result += utostr(Protocols.size());
6696 Result += "\n";
6697
6698 Result += "\t,{&_OBJC_PROTOCOL_";
6699 Result += Protocols[0]->getNameAsString();
6700 Result += " \n";
6701
6702 for (unsigned i = 1; i != Protocols.size(); i++) {
6703 Result += "\t ,&_OBJC_PROTOCOL_";
6704 Result += Protocols[i]->getNameAsString();
6705 Result += "\n";
6706 }
6707 Result += "\t }\n};\n";
6708}
6709
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006710/// hasObjCExceptionAttribute - Return true if this class or any super
6711/// class has the __objc_exception__ attribute.
6712/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6713static bool hasObjCExceptionAttribute(ASTContext &Context,
6714 const ObjCInterfaceDecl *OID) {
6715 if (OID->hasAttr<ObjCExceptionAttr>())
6716 return true;
6717 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6718 return hasObjCExceptionAttribute(Context, Super);
6719 return false;
6720}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006721
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006722void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6723 std::string &Result) {
6724 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6725
6726 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006727 if (CDecl->isImplicitInterfaceDecl())
6728 assert(false &&
6729 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006730
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006731 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006732 SmallVector<ObjCIvarDecl *, 8> IVars;
6733
6734 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6735 IVD; IVD = IVD->getNextIvar()) {
6736 // Ignore unnamed bit-fields.
6737 if (!IVD->getDeclName())
6738 continue;
6739 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006740 }
6741
Fariborz Jahanianae932952012-02-10 20:47:10 +00006742 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006743 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006744 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006745
6746 // Build _objc_method_list for class's instance methods if needed
6747 SmallVector<ObjCMethodDecl *, 32>
6748 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6749
6750 // If any of our property implementations have associated getters or
6751 // setters, produce metadata for them as well.
6752 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6753 PropEnd = IDecl->propimpl_end();
6754 Prop != PropEnd; ++Prop) {
6755 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6756 continue;
6757 if (!(*Prop)->getPropertyIvarDecl())
6758 continue;
6759 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6760 if (!PD)
6761 continue;
6762 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6763 if (!Getter->isDefined())
6764 InstanceMethods.push_back(Getter);
6765 if (PD->isReadOnly())
6766 continue;
6767 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6768 if (!Setter->isDefined())
6769 InstanceMethods.push_back(Setter);
6770 }
6771
6772 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6773 "_OBJC_$_INSTANCE_METHODS_",
6774 IDecl->getNameAsString(), true);
6775
6776 SmallVector<ObjCMethodDecl *, 32>
6777 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6778
6779 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6780 "_OBJC_$_CLASS_METHODS_",
6781 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006782
6783 // Protocols referenced in class declaration?
6784 // Protocol's super protocol list
6785 std::vector<ObjCProtocolDecl *> RefedProtocols;
6786 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6787 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6788 E = Protocols.end();
6789 I != E; ++I) {
6790 RefedProtocols.push_back(*I);
6791 // Must write out all protocol definitions in current qualifier list,
6792 // and in their nested qualifiers before writing out current definition.
6793 RewriteObjCProtocolMetaData(*I, Result);
6794 }
6795
6796 Write_protocol_list_initializer(Context, Result,
6797 RefedProtocols,
6798 "_OBJC_CLASS_PROTOCOLS_$_",
6799 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006800
6801 // Protocol's property metadata.
6802 std::vector<ObjCPropertyDecl *> ClassProperties;
6803 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6804 E = CDecl->prop_end(); I != E; ++I)
6805 ClassProperties.push_back(*I);
6806
6807 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006808 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006809 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006810 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006811
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006812
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006813 // Data for initializing _class_ro_t metaclass meta-data
6814 uint32_t flags = CLS_META;
6815 std::string InstanceSize;
6816 std::string InstanceStart;
6817
6818
6819 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6820 if (classIsHidden)
6821 flags |= OBJC2_CLS_HIDDEN;
6822
6823 if (!CDecl->getSuperClass())
6824 // class is root
6825 flags |= CLS_ROOT;
6826 InstanceSize = "sizeof(struct _class_t)";
6827 InstanceStart = InstanceSize;
6828 Write__class_ro_t_initializer(Context, Result, flags,
6829 InstanceStart, InstanceSize,
6830 ClassMethods,
6831 0,
6832 0,
6833 0,
6834 "_OBJC_METACLASS_RO_$_",
6835 CDecl->getNameAsString());
6836
6837
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006838 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006839 flags = CLS;
6840 if (classIsHidden)
6841 flags |= OBJC2_CLS_HIDDEN;
6842
6843 if (hasObjCExceptionAttribute(*Context, CDecl))
6844 flags |= CLS_EXCEPTION;
6845
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006846 if (!CDecl->getSuperClass())
6847 // class is root
6848 flags |= CLS_ROOT;
6849
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006850 InstanceSize.clear();
6851 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006852 if (!ObjCSynthesizedStructs.count(CDecl)) {
6853 InstanceSize = "0";
6854 InstanceStart = "0";
6855 }
6856 else {
6857 InstanceSize = "sizeof(struct ";
6858 InstanceSize += CDecl->getNameAsString();
6859 InstanceSize += "_IMPL)";
6860
6861 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6862 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006863 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006864 }
6865 else
6866 InstanceStart = InstanceSize;
6867 }
6868 Write__class_ro_t_initializer(Context, Result, flags,
6869 InstanceStart, InstanceSize,
6870 InstanceMethods,
6871 RefedProtocols,
6872 IVars,
6873 ClassProperties,
6874 "_OBJC_CLASS_RO_$_",
6875 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006876
6877 Write_class_t(Context, Result,
6878 "OBJC_METACLASS_$_",
6879 CDecl, /*metaclass*/true);
6880
6881 Write_class_t(Context, Result,
6882 "OBJC_CLASS_$_",
6883 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006884
6885 if (ImplementationIsNonLazy(IDecl))
6886 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006887
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006888}
6889
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006890void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6891 int ClsDefCount = ClassImplementation.size();
6892 if (!ClsDefCount)
6893 return;
6894 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6895 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6896 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6897 for (int i = 0; i < ClsDefCount; i++) {
6898 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6899 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6900 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6901 Result += CDecl->getName(); Result += ",\n";
6902 }
6903 Result += "};\n";
6904}
6905
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006906void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6907 int ClsDefCount = ClassImplementation.size();
6908 int CatDefCount = CategoryImplementation.size();
6909
6910 // For each implemented class, write out all its meta data.
6911 for (int i = 0; i < ClsDefCount; i++)
6912 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6913
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006914 RewriteClassSetupInitHook(Result);
6915
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006916 // For each implemented category, write out all its meta data.
6917 for (int i = 0; i < CatDefCount; i++)
6918 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6919
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006920 RewriteCategorySetupInitHook(Result);
6921
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006922 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006923 if (LangOpts.MicrosoftExt)
6924 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006925 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6926 Result += llvm::utostr(ClsDefCount); Result += "]";
6927 Result +=
6928 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6929 "regular,no_dead_strip\")))= {\n";
6930 for (int i = 0; i < ClsDefCount; i++) {
6931 Result += "\t&OBJC_CLASS_$_";
6932 Result += ClassImplementation[i]->getNameAsString();
6933 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006934 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006935 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006936
6937 if (!DefinedNonLazyClasses.empty()) {
6938 if (LangOpts.MicrosoftExt)
6939 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6940 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6941 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6942 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6943 Result += ",\n";
6944 }
6945 Result += "};\n";
6946 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006947 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006948
6949 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006950 if (LangOpts.MicrosoftExt)
6951 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006952 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6953 Result += llvm::utostr(CatDefCount); Result += "]";
6954 Result +=
6955 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6956 "regular,no_dead_strip\")))= {\n";
6957 for (int i = 0; i < CatDefCount; i++) {
6958 Result += "\t&_OBJC_$_CATEGORY_";
6959 Result +=
6960 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6961 Result += "_$_";
6962 Result += CategoryImplementation[i]->getNameAsString();
6963 Result += ",\n";
6964 }
6965 Result += "};\n";
6966 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006967
6968 if (!DefinedNonLazyCategories.empty()) {
6969 if (LangOpts.MicrosoftExt)
6970 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6971 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6972 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6973 Result += "\t&_OBJC_$_CATEGORY_";
6974 Result +=
6975 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6976 Result += "_$_";
6977 Result += DefinedNonLazyCategories[i]->getNameAsString();
6978 Result += ",\n";
6979 }
6980 Result += "};\n";
6981 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006982}
6983
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006984void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6985 if (LangOpts.MicrosoftExt)
6986 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6987
6988 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6989 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006990 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006991}
6992
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006993/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6994/// implementation.
6995void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6996 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006997 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006998 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6999 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007000 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007001 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7002 CDecl = CDecl->getNextClassCategory())
7003 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7004 break;
7005
7006 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007007 FullCategoryName += "_$_";
7008 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007009
7010 // Build _objc_method_list for class's instance methods if needed
7011 SmallVector<ObjCMethodDecl *, 32>
7012 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7013
7014 // If any of our property implementations have associated getters or
7015 // setters, produce metadata for them as well.
7016 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7017 PropEnd = IDecl->propimpl_end();
7018 Prop != PropEnd; ++Prop) {
7019 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7020 continue;
7021 if (!(*Prop)->getPropertyIvarDecl())
7022 continue;
7023 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
7024 if (!PD)
7025 continue;
7026 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7027 InstanceMethods.push_back(Getter);
7028 if (PD->isReadOnly())
7029 continue;
7030 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7031 InstanceMethods.push_back(Setter);
7032 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007033
Fariborz Jahanian61186122012-02-17 18:40:41 +00007034 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7035 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7036 FullCategoryName, true);
7037
7038 SmallVector<ObjCMethodDecl *, 32>
7039 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7040
7041 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7042 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7043 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007044
7045 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007046 // Protocol's super protocol list
7047 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007048 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7049 E = CDecl->protocol_end();
7050
7051 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007052 RefedProtocols.push_back(*I);
7053 // Must write out all protocol definitions in current qualifier list,
7054 // and in their nested qualifiers before writing out current definition.
7055 RewriteObjCProtocolMetaData(*I, Result);
7056 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007057
Fariborz Jahanian61186122012-02-17 18:40:41 +00007058 Write_protocol_list_initializer(Context, Result,
7059 RefedProtocols,
7060 "_OBJC_CATEGORY_PROTOCOLS_$_",
7061 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007062
Fariborz Jahanian61186122012-02-17 18:40:41 +00007063 // Protocol's property metadata.
7064 std::vector<ObjCPropertyDecl *> ClassProperties;
7065 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7066 E = CDecl->prop_end(); I != E; ++I)
7067 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007068
Fariborz Jahanian61186122012-02-17 18:40:41 +00007069 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7070 /* Container */0,
7071 "_OBJC_$_PROP_LIST_",
7072 FullCategoryName);
7073
7074 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007075 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007076 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007077 InstanceMethods,
7078 ClassMethods,
7079 RefedProtocols,
7080 ClassProperties);
7081
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007082 // Determine if this category is also "non-lazy".
7083 if (ImplementationIsNonLazy(IDecl))
7084 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007085
7086}
7087
7088void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7089 int CatDefCount = CategoryImplementation.size();
7090 if (!CatDefCount)
7091 return;
7092 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7093 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7094 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7095 for (int i = 0; i < CatDefCount; i++) {
7096 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7097 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7098 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7099 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7100 Result += ClassDecl->getName();
7101 Result += "_$_";
7102 Result += CatDecl->getName();
7103 Result += ",\n";
7104 }
7105 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007106}
7107
7108// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7109/// class methods.
7110template<typename MethodIterator>
7111void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7112 MethodIterator MethodEnd,
7113 bool IsInstanceMethod,
7114 StringRef prefix,
7115 StringRef ClassName,
7116 std::string &Result) {
7117 if (MethodBegin == MethodEnd) return;
7118
7119 if (!objc_impl_method) {
7120 /* struct _objc_method {
7121 SEL _cmd;
7122 char *method_types;
7123 void *_imp;
7124 }
7125 */
7126 Result += "\nstruct _objc_method {\n";
7127 Result += "\tSEL _cmd;\n";
7128 Result += "\tchar *method_types;\n";
7129 Result += "\tvoid *_imp;\n";
7130 Result += "};\n";
7131
7132 objc_impl_method = true;
7133 }
7134
7135 // Build _objc_method_list for class's methods if needed
7136
7137 /* struct {
7138 struct _objc_method_list *next_method;
7139 int method_count;
7140 struct _objc_method method_list[];
7141 }
7142 */
7143 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007144 Result += "\n";
7145 if (LangOpts.MicrosoftExt) {
7146 if (IsInstanceMethod)
7147 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7148 else
7149 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7150 }
7151 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007152 Result += "\tstruct _objc_method_list *next_method;\n";
7153 Result += "\tint method_count;\n";
7154 Result += "\tstruct _objc_method method_list[";
7155 Result += utostr(NumMethods);
7156 Result += "];\n} _OBJC_";
7157 Result += prefix;
7158 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7159 Result += "_METHODS_";
7160 Result += ClassName;
7161 Result += " __attribute__ ((used, section (\"__OBJC, __";
7162 Result += IsInstanceMethod ? "inst" : "cls";
7163 Result += "_meth\")))= ";
7164 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7165
7166 Result += "\t,{{(SEL)\"";
7167 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7168 std::string MethodTypeString;
7169 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7170 Result += "\", \"";
7171 Result += MethodTypeString;
7172 Result += "\", (void *)";
7173 Result += MethodInternalNames[*MethodBegin];
7174 Result += "}\n";
7175 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7176 Result += "\t ,{(SEL)\"";
7177 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7178 std::string MethodTypeString;
7179 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7180 Result += "\", \"";
7181 Result += MethodTypeString;
7182 Result += "\", (void *)";
7183 Result += MethodInternalNames[*MethodBegin];
7184 Result += "}\n";
7185 }
7186 Result += "\t }\n};\n";
7187}
7188
7189Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7190 SourceRange OldRange = IV->getSourceRange();
7191 Expr *BaseExpr = IV->getBase();
7192
7193 // Rewrite the base, but without actually doing replaces.
7194 {
7195 DisableReplaceStmtScope S(*this);
7196 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7197 IV->setBase(BaseExpr);
7198 }
7199
7200 ObjCIvarDecl *D = IV->getDecl();
7201
7202 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007203
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007204 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7205 const ObjCInterfaceType *iFaceDecl =
7206 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7207 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7208 // lookup which class implements the instance variable.
7209 ObjCInterfaceDecl *clsDeclared = 0;
7210 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7211 clsDeclared);
7212 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7213
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007214 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007215 std::string IvarOffsetName;
7216 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7217
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007218 ReferencedIvars[clsDeclared].insert(D);
7219
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007220 // cast offset to "char *".
7221 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7222 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007223 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007224 BaseExpr);
7225 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7226 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7227 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007228 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7229 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007230 SourceLocation());
7231 BinaryOperator *addExpr =
7232 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7233 Context->getPointerType(Context->CharTy),
7234 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007235 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007236 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7237 SourceLocation(),
7238 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007239 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007240 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007241 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007242
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007243 castExpr = NoTypeInfoCStyleCastExpr(Context,
7244 castT,
7245 CK_BitCast,
7246 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007247 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007248 VK_LValue, OK_Ordinary,
7249 SourceLocation());
7250 PE = new (Context) ParenExpr(OldRange.getBegin(),
7251 OldRange.getEnd(),
7252 Exp);
7253
7254 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007255 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007256
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007257 ReplaceStmtWithRange(IV, Replacement, OldRange);
7258 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007259}