blob: b10d64134b58849e7db7f0ba6022cb7159444cfd [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;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000111 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000113 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
114 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
115
116 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
117 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
118
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000119 SmallVector<Stmt *, 32> Stmts;
120 SmallVector<int, 8> ObjCBcLabelNo;
121 // Remember all the @protocol(<expr>) expressions.
122 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
123
124 llvm::DenseSet<uint64_t> CopyDestroyCache;
125
126 // Block expressions.
127 SmallVector<BlockExpr *, 32> Blocks;
128 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000129 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000130
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
133 // Block related declarations.
134 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
135 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
136 SmallVector<ValueDecl *, 8> BlockByRefDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
138 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
139 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
140 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
141
142 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000143 llvm::DenseMap<ObjCInterfaceDecl *,
144 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
145
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000146 // This maps an original source AST to it's rewritten form. This allows
147 // us to avoid rewriting the same node twice (which is very uncommon).
148 // This is needed to support some of the exotic property rewriting.
149 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
150
151 // Needed for header files being rewritten
152 bool IsHeader;
153 bool SilenceRewriteMacroWarning;
154 bool objc_impl_method;
155
156 bool DisableReplaceStmt;
157 class DisableReplaceStmtScope {
158 RewriteModernObjC &R;
159 bool SavedValue;
160
161 public:
162 DisableReplaceStmtScope(RewriteModernObjC &R)
163 : R(R), SavedValue(R.DisableReplaceStmt) {
164 R.DisableReplaceStmt = true;
165 }
166 ~DisableReplaceStmtScope() {
167 R.DisableReplaceStmt = SavedValue;
168 }
169 };
170 void InitializeCommon(ASTContext &context);
171
172 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000173 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000174 // Top Level Driver code.
175 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
176 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
177 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
178 if (!Class->isThisDeclarationADefinition()) {
179 RewriteForwardClassDecl(D);
180 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000181 } else {
182 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000183 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000184 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000185 }
186 }
187
188 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
189 if (!Proto->isThisDeclarationADefinition()) {
190 RewriteForwardProtocolDecl(D);
191 break;
192 }
193 }
194
195 HandleTopLevelSingleDecl(*I);
196 }
197 return true;
198 }
199 void HandleTopLevelSingleDecl(Decl *D);
200 void HandleDeclInMainFile(Decl *D);
201 RewriteModernObjC(std::string inFile, raw_ostream *OS,
202 DiagnosticsEngine &D, const LangOptions &LOpts,
203 bool silenceMacroWarn);
204
205 ~RewriteModernObjC() {}
206
207 virtual void HandleTranslationUnit(ASTContext &C);
208
209 void ReplaceStmt(Stmt *Old, Stmt *New) {
210 Stmt *ReplacingStmt = ReplacedNodes[Old];
211
212 if (ReplacingStmt)
213 return; // We can't rewrite the same node twice.
214
215 if (DisableReplaceStmt)
216 return;
217
218 // If replacement succeeded or warning disabled return with no warning.
219 if (!Rewrite.ReplaceStmt(Old, New)) {
220 ReplacedNodes[Old] = New;
221 return;
222 }
223 if (SilenceRewriteMacroWarning)
224 return;
225 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
226 << Old->getSourceRange();
227 }
228
229 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
230 if (DisableReplaceStmt)
231 return;
232
233 // Measure the old text.
234 int Size = Rewrite.getRangeSize(SrcRange);
235 if (Size == -1) {
236 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
237 << Old->getSourceRange();
238 return;
239 }
240 // Get the new text.
241 std::string SStr;
242 llvm::raw_string_ostream S(SStr);
243 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
244 const std::string &Str = S.str();
245
246 // If replacement succeeded or warning disabled return with no warning.
247 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
248 ReplacedNodes[Old] = New;
249 return;
250 }
251 if (SilenceRewriteMacroWarning)
252 return;
253 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
254 << Old->getSourceRange();
255 }
256
257 void InsertText(SourceLocation Loc, StringRef Str,
258 bool InsertAfter = true) {
259 // If insertion succeeded or warning disabled return with no warning.
260 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
261 SilenceRewriteMacroWarning)
262 return;
263
264 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
265 }
266
267 void ReplaceText(SourceLocation Start, unsigned OrigLength,
268 StringRef Str) {
269 // If removal succeeded or warning disabled return with no warning.
270 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
271 SilenceRewriteMacroWarning)
272 return;
273
274 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
275 }
276
277 // Syntactic Rewriting.
278 void RewriteRecordBody(RecordDecl *RD);
279 void RewriteInclude();
280 void RewriteForwardClassDecl(DeclGroupRef D);
281 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
282 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
283 const std::string &typedefString);
284 void RewriteImplementations();
285 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
286 ObjCImplementationDecl *IMD,
287 ObjCCategoryImplDecl *CID);
288 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
289 void RewriteImplementationDecl(Decl *Dcl);
290 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
291 ObjCMethodDecl *MDecl, std::string &ResultStr);
292 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
293 const FunctionType *&FPRetType);
294 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
295 ValueDecl *VD, bool def=false);
296 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
297 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
298 void RewriteForwardProtocolDecl(DeclGroupRef D);
299 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
300 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
301 void RewriteProperty(ObjCPropertyDecl *prop);
302 void RewriteFunctionDecl(FunctionDecl *FD);
303 void RewriteBlockPointerType(std::string& Str, QualType Type);
304 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
305 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
306 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
307 void RewriteTypeOfDecl(VarDecl *VD);
308 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
309
310 // Expression Rewriting.
311 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
312 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
313 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
314 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
316 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
317 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
318 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
319 void RewriteTryReturnStmts(Stmt *S);
320 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
321 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
322 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
323 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
324 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
325 SourceLocation OrigEnd);
326 Stmt *RewriteBreakStmt(BreakStmt *S);
327 Stmt *RewriteContinueStmt(ContinueStmt *S);
328 void RewriteCastExpr(CStyleCastExpr *CE);
329
330 // Block rewriting.
331 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
332
333 // Block specific rewrite rules.
334 void RewriteBlockPointerDecl(NamedDecl *VD);
335 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000336 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000337 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
338 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
339
340 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
341 std::string &Result);
342
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000343 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
344
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000345 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
346
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000347 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
348 std::string &Result);
349
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000350 virtual void Initialize(ASTContext &context);
351
352 // Misc. AST transformation routines. Somtimes they end up calling
353 // rewriting routines on the new ASTs.
354 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
355 Expr **args, unsigned nargs,
356 SourceLocation StartLoc=SourceLocation(),
357 SourceLocation EndLoc=SourceLocation());
358
359 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 void SynthCountByEnumWithState(std::string &buf);
364 void SynthMsgSendFunctionDecl();
365 void SynthMsgSendSuperFunctionDecl();
366 void SynthMsgSendStretFunctionDecl();
367 void SynthMsgSendFpretFunctionDecl();
368 void SynthMsgSendSuperStretFunctionDecl();
369 void SynthGetClassFunctionDecl();
370 void SynthGetMetaClassFunctionDecl();
371 void SynthGetSuperClassFunctionDecl();
372 void SynthSelGetUidFunctionDecl();
373 void SynthSuperContructorFunctionDecl();
374
375 // Rewriting metadata
376 template<typename MethodIterator>
377 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
378 MethodIterator MethodEnd,
379 bool IsInstanceMethod,
380 StringRef prefix,
381 StringRef ClassName,
382 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000383 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
384 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000385 virtual void RewriteObjCProtocolListMetaData(
386 const ObjCList<ObjCProtocolDecl> &Prots,
387 StringRef prefix, StringRef ClassName, std::string &Result);
388 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
389 std::string &Result);
390 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000391 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000392 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
393 std::string &Result);
394
395 // Rewriting ivar
396 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
397 std::string &Result);
398 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
399
400
401 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
402 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
403 StringRef funcName, std::string Tag);
404 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
405 StringRef funcName, std::string Tag);
406 std::string SynthesizeBlockImpl(BlockExpr *CE,
407 std::string Tag, std::string Desc);
408 std::string SynthesizeBlockDescriptor(std::string DescTag,
409 std::string ImplTag,
410 int i, StringRef funcName,
411 unsigned hasCopy);
412 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
413 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
414 StringRef FunName);
415 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
416 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000417 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000418
419 // Misc. helper routines.
420 QualType getProtocolType();
421 void WarnAboutReturnGotoStmts(Stmt *S);
422 void HasReturnStmts(Stmt *S, bool &hasReturns);
423 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
424 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
425 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
426
427 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
428 void CollectBlockDeclRefInfo(BlockExpr *Exp);
429 void GetBlockDeclRefExprs(Stmt *S);
430 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000431 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000432 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
433
434 // We avoid calling Type::isBlockPointerType(), since it operates on the
435 // canonical type. We only care if the top-level type is a closure pointer.
436 bool isTopLevelBlockPointerType(QualType T) {
437 return isa<BlockPointerType>(T);
438 }
439
440 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
441 /// to a function pointer type and upon success, returns true; false
442 /// otherwise.
443 bool convertBlockPointerToFunctionPointer(QualType &T) {
444 if (isTopLevelBlockPointerType(T)) {
445 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
446 T = Context->getPointerType(BPT->getPointeeType());
447 return true;
448 }
449 return false;
450 }
451
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000452 bool convertObjCTypeToCStyleType(QualType &T);
453
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000454 bool needToScanForQualifiers(QualType T);
455 QualType getSuperStructType();
456 QualType getConstantStringStructType();
457 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
458 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
459
460 void convertToUnqualifiedObjCType(QualType &T) {
461 if (T->isObjCQualifiedIdType())
462 T = Context->getObjCIdType();
463 else if (T->isObjCQualifiedClassType())
464 T = Context->getObjCClassType();
465 else if (T->isObjCObjectPointerType() &&
466 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
467 if (const ObjCObjectPointerType * OBJPT =
468 T->getAsObjCInterfacePointerType()) {
469 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
470 T = QualType(IFaceT, 0);
471 T = Context->getPointerType(T);
472 }
473 }
474 }
475
476 // FIXME: This predicate seems like it would be useful to add to ASTContext.
477 bool isObjCType(QualType T) {
478 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
479 return false;
480
481 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
482
483 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
484 OCT == Context->getCanonicalType(Context->getObjCClassType()))
485 return true;
486
487 if (const PointerType *PT = OCT->getAs<PointerType>()) {
488 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
489 PT->getPointeeType()->isObjCQualifiedIdType())
490 return true;
491 }
492 return false;
493 }
494 bool PointerTypeTakesAnyBlockArguments(QualType QT);
495 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
496 void GetExtentOfArgList(const char *Name, const char *&LParen,
497 const char *&RParen);
498
499 void QuoteDoublequotes(std::string &From, std::string &To) {
500 for (unsigned i = 0; i < From.length(); i++) {
501 if (From[i] == '"')
502 To += "\\\"";
503 else
504 To += From[i];
505 }
506 }
507
508 QualType getSimpleFunctionType(QualType result,
509 const QualType *args,
510 unsigned numArgs,
511 bool variadic = false) {
512 if (result == Context->getObjCInstanceType())
513 result = Context->getObjCIdType();
514 FunctionProtoType::ExtProtoInfo fpi;
515 fpi.Variadic = variadic;
516 return Context->getFunctionType(result, args, numArgs, fpi);
517 }
518
519 // Helper function: create a CStyleCastExpr with trivial type source info.
520 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
521 CastKind Kind, Expr *E) {
522 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
523 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
524 SourceLocation(), SourceLocation());
525 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000526
527 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
528 IdentifierInfo* II = &Context->Idents.get("load");
529 Selector LoadSel = Context->Selectors.getSelector(0, &II);
530 return OD->getClassMethod(LoadSel) != 0;
531 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000532 };
533
534}
535
536void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
537 NamedDecl *D) {
538 if (const FunctionProtoType *fproto
539 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
540 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
541 E = fproto->arg_type_end(); I && (I != E); ++I)
542 if (isTopLevelBlockPointerType(*I)) {
543 // All the args are checked/rewritten. Don't call twice!
544 RewriteBlockPointerDecl(D);
545 break;
546 }
547 }
548}
549
550void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
551 const PointerType *PT = funcType->getAs<PointerType>();
552 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
553 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
554}
555
556static bool IsHeaderFile(const std::string &Filename) {
557 std::string::size_type DotPos = Filename.rfind('.');
558
559 if (DotPos == std::string::npos) {
560 // no file extension
561 return false;
562 }
563
564 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
565 // C header: .h
566 // C++ header: .hh or .H;
567 return Ext == "h" || Ext == "hh" || Ext == "H";
568}
569
570RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
571 DiagnosticsEngine &D, const LangOptions &LOpts,
572 bool silenceMacroWarn)
573 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
574 SilenceRewriteMacroWarning(silenceMacroWarn) {
575 IsHeader = IsHeaderFile(inFile);
576 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
577 "rewriting sub-expression within a macro (may not be correct)");
578 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
579 DiagnosticsEngine::Warning,
580 "rewriter doesn't support user-specified control flow semantics "
581 "for @try/@finally (code may not execute properly)");
582}
583
584ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
585 raw_ostream* OS,
586 DiagnosticsEngine &Diags,
587 const LangOptions &LOpts,
588 bool SilenceRewriteMacroWarning) {
589 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
590}
591
592void RewriteModernObjC::InitializeCommon(ASTContext &context) {
593 Context = &context;
594 SM = &Context->getSourceManager();
595 TUDecl = Context->getTranslationUnitDecl();
596 MsgSendFunctionDecl = 0;
597 MsgSendSuperFunctionDecl = 0;
598 MsgSendStretFunctionDecl = 0;
599 MsgSendSuperStretFunctionDecl = 0;
600 MsgSendFpretFunctionDecl = 0;
601 GetClassFunctionDecl = 0;
602 GetMetaClassFunctionDecl = 0;
603 GetSuperClassFunctionDecl = 0;
604 SelGetUidFunctionDecl = 0;
605 CFStringFunctionDecl = 0;
606 ConstantStringClassReference = 0;
607 NSStringRecord = 0;
608 CurMethodDef = 0;
609 CurFunctionDef = 0;
610 CurFunctionDeclToDeclareForBlock = 0;
611 GlobalVarDecl = 0;
612 SuperStructDecl = 0;
613 ProtocolTypeDecl = 0;
614 ConstantStringDecl = 0;
615 BcLabelCount = 0;
616 SuperContructorFunctionDecl = 0;
617 NumObjCStringLiterals = 0;
618 PropParentMap = 0;
619 CurrentBody = 0;
620 DisableReplaceStmt = false;
621 objc_impl_method = false;
622
623 // Get the ID and start/end of the main file.
624 MainFileID = SM->getMainFileID();
625 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
626 MainFileStart = MainBuf->getBufferStart();
627 MainFileEnd = MainBuf->getBufferEnd();
628
David Blaikie4e4d0842012-03-11 07:00:24 +0000629 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000630}
631
632//===----------------------------------------------------------------------===//
633// Top Level Driver Code
634//===----------------------------------------------------------------------===//
635
636void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
637 if (Diags.hasErrorOccurred())
638 return;
639
640 // Two cases: either the decl could be in the main file, or it could be in a
641 // #included file. If the former, rewrite it now. If the later, check to see
642 // if we rewrote the #include/#import.
643 SourceLocation Loc = D->getLocation();
644 Loc = SM->getExpansionLoc(Loc);
645
646 // If this is for a builtin, ignore it.
647 if (Loc.isInvalid()) return;
648
649 // Look for built-in declarations that we need to refer during the rewrite.
650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
651 RewriteFunctionDecl(FD);
652 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
653 // declared in <Foundation/NSString.h>
654 if (FVD->getName() == "_NSConstantStringClassReference") {
655 ConstantStringClassReference = FVD;
656 return;
657 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000658 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
659 RewriteCategoryDecl(CD);
660 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
661 if (PD->isThisDeclarationADefinition())
662 RewriteProtocolDecl(PD);
663 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
664 // Recurse into linkage specifications
665 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
666 DIEnd = LSD->decls_end();
667 DI != DIEnd; ) {
668 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
669 if (!IFace->isThisDeclarationADefinition()) {
670 SmallVector<Decl *, 8> DG;
671 SourceLocation StartLoc = IFace->getLocStart();
672 do {
673 if (isa<ObjCInterfaceDecl>(*DI) &&
674 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
675 StartLoc == (*DI)->getLocStart())
676 DG.push_back(*DI);
677 else
678 break;
679
680 ++DI;
681 } while (DI != DIEnd);
682 RewriteForwardClassDecl(DG);
683 continue;
684 }
685 }
686
687 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
688 if (!Proto->isThisDeclarationADefinition()) {
689 SmallVector<Decl *, 8> DG;
690 SourceLocation StartLoc = Proto->getLocStart();
691 do {
692 if (isa<ObjCProtocolDecl>(*DI) &&
693 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
694 StartLoc == (*DI)->getLocStart())
695 DG.push_back(*DI);
696 else
697 break;
698
699 ++DI;
700 } while (DI != DIEnd);
701 RewriteForwardProtocolDecl(DG);
702 continue;
703 }
704 }
705
706 HandleTopLevelSingleDecl(*DI);
707 ++DI;
708 }
709 }
710 // If we have a decl in the main file, see if we should rewrite it.
711 if (SM->isFromMainFile(Loc))
712 return HandleDeclInMainFile(D);
713}
714
715//===----------------------------------------------------------------------===//
716// Syntactic (non-AST) Rewriting Code
717//===----------------------------------------------------------------------===//
718
719void RewriteModernObjC::RewriteInclude() {
720 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
721 StringRef MainBuf = SM->getBufferData(MainFileID);
722 const char *MainBufStart = MainBuf.begin();
723 const char *MainBufEnd = MainBuf.end();
724 size_t ImportLen = strlen("import");
725
726 // Loop over the whole file, looking for includes.
727 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
728 if (*BufPtr == '#') {
729 if (++BufPtr == MainBufEnd)
730 return;
731 while (*BufPtr == ' ' || *BufPtr == '\t')
732 if (++BufPtr == MainBufEnd)
733 return;
734 if (!strncmp(BufPtr, "import", ImportLen)) {
735 // replace import with include
736 SourceLocation ImportLoc =
737 LocStart.getLocWithOffset(BufPtr-MainBufStart);
738 ReplaceText(ImportLoc, ImportLen, "include");
739 BufPtr += ImportLen;
740 }
741 }
742 }
743}
744
745static std::string getIvarAccessString(ObjCIvarDecl *OID) {
746 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
747 std::string S;
748 S = "((struct ";
749 S += ClassDecl->getIdentifier()->getName();
750 S += "_IMPL *)self)->";
751 S += OID->getName();
752 return S;
753}
754
755void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
756 ObjCImplementationDecl *IMD,
757 ObjCCategoryImplDecl *CID) {
758 static bool objcGetPropertyDefined = false;
759 static bool objcSetPropertyDefined = false;
760 SourceLocation startLoc = PID->getLocStart();
761 InsertText(startLoc, "// ");
762 const char *startBuf = SM->getCharacterData(startLoc);
763 assert((*startBuf == '@') && "bogus @synthesize location");
764 const char *semiBuf = strchr(startBuf, ';');
765 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
766 SourceLocation onePastSemiLoc =
767 startLoc.getLocWithOffset(semiBuf-startBuf+1);
768
769 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
770 return; // FIXME: is this correct?
771
772 // Generate the 'getter' function.
773 ObjCPropertyDecl *PD = PID->getPropertyDecl();
774 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
775
776 if (!OID)
777 return;
778 unsigned Attributes = PD->getPropertyAttributes();
779 if (!PD->getGetterMethodDecl()->isDefined()) {
780 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
781 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
782 ObjCPropertyDecl::OBJC_PR_copy));
783 std::string Getr;
784 if (GenGetProperty && !objcGetPropertyDefined) {
785 objcGetPropertyDefined = true;
786 // FIXME. Is this attribute correct in all cases?
787 Getr = "\nextern \"C\" __declspec(dllimport) "
788 "id objc_getProperty(id, SEL, long, bool);\n";
789 }
790 RewriteObjCMethodDecl(OID->getContainingInterface(),
791 PD->getGetterMethodDecl(), Getr);
792 Getr += "{ ";
793 // Synthesize an explicit cast to gain access to the ivar.
794 // See objc-act.c:objc_synthesize_new_getter() for details.
795 if (GenGetProperty) {
796 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
797 Getr += "typedef ";
798 const FunctionType *FPRetType = 0;
799 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
800 FPRetType);
801 Getr += " _TYPE";
802 if (FPRetType) {
803 Getr += ")"; // close the precedence "scope" for "*".
804
805 // Now, emit the argument types (if any).
806 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
807 Getr += "(";
808 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
809 if (i) Getr += ", ";
810 std::string ParamStr = FT->getArgType(i).getAsString(
811 Context->getPrintingPolicy());
812 Getr += ParamStr;
813 }
814 if (FT->isVariadic()) {
815 if (FT->getNumArgs()) Getr += ", ";
816 Getr += "...";
817 }
818 Getr += ")";
819 } else
820 Getr += "()";
821 }
822 Getr += ";\n";
823 Getr += "return (_TYPE)";
824 Getr += "objc_getProperty(self, _cmd, ";
825 RewriteIvarOffsetComputation(OID, Getr);
826 Getr += ", 1)";
827 }
828 else
829 Getr += "return " + getIvarAccessString(OID);
830 Getr += "; }";
831 InsertText(onePastSemiLoc, Getr);
832 }
833
834 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
835 return;
836
837 // Generate the 'setter' function.
838 std::string Setr;
839 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
840 ObjCPropertyDecl::OBJC_PR_copy);
841 if (GenSetProperty && !objcSetPropertyDefined) {
842 objcSetPropertyDefined = true;
843 // FIXME. Is this attribute correct in all cases?
844 Setr = "\nextern \"C\" __declspec(dllimport) "
845 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
846 }
847
848 RewriteObjCMethodDecl(OID->getContainingInterface(),
849 PD->getSetterMethodDecl(), Setr);
850 Setr += "{ ";
851 // Synthesize an explicit cast to initialize the ivar.
852 // See objc-act.c:objc_synthesize_new_setter() for details.
853 if (GenSetProperty) {
854 Setr += "objc_setProperty (self, _cmd, ";
855 RewriteIvarOffsetComputation(OID, Setr);
856 Setr += ", (id)";
857 Setr += PD->getName();
858 Setr += ", ";
859 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
860 Setr += "0, ";
861 else
862 Setr += "1, ";
863 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
864 Setr += "1)";
865 else
866 Setr += "0)";
867 }
868 else {
869 Setr += getIvarAccessString(OID) + " = ";
870 Setr += PD->getName();
871 }
872 Setr += "; }";
873 InsertText(onePastSemiLoc, Setr);
874}
875
876static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
877 std::string &typedefString) {
878 typedefString += "#ifndef _REWRITER_typedef_";
879 typedefString += ForwardDecl->getNameAsString();
880 typedefString += "\n";
881 typedefString += "#define _REWRITER_typedef_";
882 typedefString += ForwardDecl->getNameAsString();
883 typedefString += "\n";
884 typedefString += "typedef struct objc_object ";
885 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000886 // typedef struct { } _objc_exc_Classname;
887 typedefString += ";\ntypedef struct {} _objc_exc_";
888 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000889 typedefString += ";\n#endif\n";
890}
891
892void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
893 const std::string &typedefString) {
894 SourceLocation startLoc = ClassDecl->getLocStart();
895 const char *startBuf = SM->getCharacterData(startLoc);
896 const char *semiPtr = strchr(startBuf, ';');
897 // Replace the @class with typedefs corresponding to the classes.
898 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
899}
900
901void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
902 std::string typedefString;
903 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
904 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
905 if (I == D.begin()) {
906 // Translate to typedef's that forward reference structs with the same name
907 // as the class. As a convenience, we include the original declaration
908 // as a comment.
909 typedefString += "// @class ";
910 typedefString += ForwardDecl->getNameAsString();
911 typedefString += ";\n";
912 }
913 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
914 }
915 DeclGroupRef::iterator I = D.begin();
916 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
917}
918
919void RewriteModernObjC::RewriteForwardClassDecl(
920 const llvm::SmallVector<Decl*, 8> &D) {
921 std::string typedefString;
922 for (unsigned i = 0; i < D.size(); i++) {
923 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
924 if (i == 0) {
925 typedefString += "// @class ";
926 typedefString += ForwardDecl->getNameAsString();
927 typedefString += ";\n";
928 }
929 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
930 }
931 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
932}
933
934void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
935 // When method is a synthesized one, such as a getter/setter there is
936 // nothing to rewrite.
937 if (Method->isImplicit())
938 return;
939 SourceLocation LocStart = Method->getLocStart();
940 SourceLocation LocEnd = Method->getLocEnd();
941
942 if (SM->getExpansionLineNumber(LocEnd) >
943 SM->getExpansionLineNumber(LocStart)) {
944 InsertText(LocStart, "#if 0\n");
945 ReplaceText(LocEnd, 1, ";\n#endif\n");
946 } else {
947 InsertText(LocStart, "// ");
948 }
949}
950
951void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
952 SourceLocation Loc = prop->getAtLoc();
953
954 ReplaceText(Loc, 0, "// ");
955 // FIXME: handle properties that are declared across multiple lines.
956}
957
958void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
959 SourceLocation LocStart = CatDecl->getLocStart();
960
961 // FIXME: handle category headers that are declared across multiple lines.
962 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000963 if (CatDecl->getIvarLBraceLoc().isValid())
964 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000965 for (ObjCCategoryDecl::ivar_iterator
966 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
967 ObjCIvarDecl *Ivar = (*I);
968 SourceLocation LocStart = Ivar->getLocStart();
969 ReplaceText(LocStart, 0, "// ");
970 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000971 if (CatDecl->getIvarRBraceLoc().isValid())
972 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
973
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000974 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
975 E = CatDecl->prop_end(); I != E; ++I)
976 RewriteProperty(*I);
977
978 for (ObjCCategoryDecl::instmeth_iterator
979 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
980 I != E; ++I)
981 RewriteMethodDeclaration(*I);
982 for (ObjCCategoryDecl::classmeth_iterator
983 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
984 I != E; ++I)
985 RewriteMethodDeclaration(*I);
986
987 // Lastly, comment out the @end.
988 ReplaceText(CatDecl->getAtEndRange().getBegin(),
989 strlen("@end"), "/* @end */");
990}
991
992void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
993 SourceLocation LocStart = PDecl->getLocStart();
994 assert(PDecl->isThisDeclarationADefinition());
995
996 // FIXME: handle protocol headers that are declared across multiple lines.
997 ReplaceText(LocStart, 0, "// ");
998
999 for (ObjCProtocolDecl::instmeth_iterator
1000 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1001 I != E; ++I)
1002 RewriteMethodDeclaration(*I);
1003 for (ObjCProtocolDecl::classmeth_iterator
1004 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1005 I != E; ++I)
1006 RewriteMethodDeclaration(*I);
1007
1008 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1009 E = PDecl->prop_end(); I != E; ++I)
1010 RewriteProperty(*I);
1011
1012 // Lastly, comment out the @end.
1013 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1014 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1015
1016 // Must comment out @optional/@required
1017 const char *startBuf = SM->getCharacterData(LocStart);
1018 const char *endBuf = SM->getCharacterData(LocEnd);
1019 for (const char *p = startBuf; p < endBuf; p++) {
1020 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1021 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1022 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1023
1024 }
1025 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1026 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1027 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1028
1029 }
1030 }
1031}
1032
1033void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1034 SourceLocation LocStart = (*D.begin())->getLocStart();
1035 if (LocStart.isInvalid())
1036 llvm_unreachable("Invalid SourceLocation");
1037 // FIXME: handle forward protocol that are declared across multiple lines.
1038 ReplaceText(LocStart, 0, "// ");
1039}
1040
1041void
1042RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1043 SourceLocation LocStart = DG[0]->getLocStart();
1044 if (LocStart.isInvalid())
1045 llvm_unreachable("Invalid SourceLocation");
1046 // FIXME: handle forward protocol that are declared across multiple lines.
1047 ReplaceText(LocStart, 0, "// ");
1048}
1049
1050void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1051 const FunctionType *&FPRetType) {
1052 if (T->isObjCQualifiedIdType())
1053 ResultStr += "id";
1054 else if (T->isFunctionPointerType() ||
1055 T->isBlockPointerType()) {
1056 // needs special handling, since pointer-to-functions have special
1057 // syntax (where a decaration models use).
1058 QualType retType = T;
1059 QualType PointeeTy;
1060 if (const PointerType* PT = retType->getAs<PointerType>())
1061 PointeeTy = PT->getPointeeType();
1062 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1063 PointeeTy = BPT->getPointeeType();
1064 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1065 ResultStr += FPRetType->getResultType().getAsString(
1066 Context->getPrintingPolicy());
1067 ResultStr += "(*";
1068 }
1069 } else
1070 ResultStr += T.getAsString(Context->getPrintingPolicy());
1071}
1072
1073void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1074 ObjCMethodDecl *OMD,
1075 std::string &ResultStr) {
1076 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1077 const FunctionType *FPRetType = 0;
1078 ResultStr += "\nstatic ";
1079 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1080 ResultStr += " ";
1081
1082 // Unique method name
1083 std::string NameStr;
1084
1085 if (OMD->isInstanceMethod())
1086 NameStr += "_I_";
1087 else
1088 NameStr += "_C_";
1089
1090 NameStr += IDecl->getNameAsString();
1091 NameStr += "_";
1092
1093 if (ObjCCategoryImplDecl *CID =
1094 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1095 NameStr += CID->getNameAsString();
1096 NameStr += "_";
1097 }
1098 // Append selector names, replacing ':' with '_'
1099 {
1100 std::string selString = OMD->getSelector().getAsString();
1101 int len = selString.size();
1102 for (int i = 0; i < len; i++)
1103 if (selString[i] == ':')
1104 selString[i] = '_';
1105 NameStr += selString;
1106 }
1107 // Remember this name for metadata emission
1108 MethodInternalNames[OMD] = NameStr;
1109 ResultStr += NameStr;
1110
1111 // Rewrite arguments
1112 ResultStr += "(";
1113
1114 // invisible arguments
1115 if (OMD->isInstanceMethod()) {
1116 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1117 selfTy = Context->getPointerType(selfTy);
1118 if (!LangOpts.MicrosoftExt) {
1119 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1120 ResultStr += "struct ";
1121 }
1122 // When rewriting for Microsoft, explicitly omit the structure name.
1123 ResultStr += IDecl->getNameAsString();
1124 ResultStr += " *";
1125 }
1126 else
1127 ResultStr += Context->getObjCClassType().getAsString(
1128 Context->getPrintingPolicy());
1129
1130 ResultStr += " self, ";
1131 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1132 ResultStr += " _cmd";
1133
1134 // Method arguments.
1135 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1136 E = OMD->param_end(); PI != E; ++PI) {
1137 ParmVarDecl *PDecl = *PI;
1138 ResultStr += ", ";
1139 if (PDecl->getType()->isObjCQualifiedIdType()) {
1140 ResultStr += "id ";
1141 ResultStr += PDecl->getNameAsString();
1142 } else {
1143 std::string Name = PDecl->getNameAsString();
1144 QualType QT = PDecl->getType();
1145 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1146 if (convertBlockPointerToFunctionPointer(QT))
1147 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1148 else
1149 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1150 ResultStr += Name;
1151 }
1152 }
1153 if (OMD->isVariadic())
1154 ResultStr += ", ...";
1155 ResultStr += ") ";
1156
1157 if (FPRetType) {
1158 ResultStr += ")"; // close the precedence "scope" for "*".
1159
1160 // Now, emit the argument types (if any).
1161 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1162 ResultStr += "(";
1163 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1164 if (i) ResultStr += ", ";
1165 std::string ParamStr = FT->getArgType(i).getAsString(
1166 Context->getPrintingPolicy());
1167 ResultStr += ParamStr;
1168 }
1169 if (FT->isVariadic()) {
1170 if (FT->getNumArgs()) ResultStr += ", ";
1171 ResultStr += "...";
1172 }
1173 ResultStr += ")";
1174 } else {
1175 ResultStr += "()";
1176 }
1177 }
1178}
1179void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1180 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1181 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1182
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001183 if (IMD) {
1184 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001185 if (IMD->getIvarLBraceLoc().isValid())
1186 InsertText(IMD->getIvarLBraceLoc(), "// ");
1187 for (ObjCImplementationDecl::ivar_iterator
1188 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1189 ObjCIvarDecl *Ivar = (*I);
1190 SourceLocation LocStart = Ivar->getLocStart();
1191 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001192 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001193 if (IMD->getIvarRBraceLoc().isValid())
1194 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001195 }
1196 else
1197 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001198
1199 for (ObjCCategoryImplDecl::instmeth_iterator
1200 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1201 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1202 I != E; ++I) {
1203 std::string ResultStr;
1204 ObjCMethodDecl *OMD = *I;
1205 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1206 SourceLocation LocStart = OMD->getLocStart();
1207 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1208
1209 const char *startBuf = SM->getCharacterData(LocStart);
1210 const char *endBuf = SM->getCharacterData(LocEnd);
1211 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1212 }
1213
1214 for (ObjCCategoryImplDecl::classmeth_iterator
1215 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1216 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1217 I != E; ++I) {
1218 std::string ResultStr;
1219 ObjCMethodDecl *OMD = *I;
1220 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1221 SourceLocation LocStart = OMD->getLocStart();
1222 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1223
1224 const char *startBuf = SM->getCharacterData(LocStart);
1225 const char *endBuf = SM->getCharacterData(LocEnd);
1226 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1227 }
1228 for (ObjCCategoryImplDecl::propimpl_iterator
1229 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1230 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1231 I != E; ++I) {
1232 RewritePropertyImplDecl(*I, IMD, CID);
1233 }
1234
1235 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1236}
1237
1238void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001239 // Do not synthesize more than once.
1240 if (ObjCSynthesizedStructs.count(ClassDecl))
1241 return;
1242 // Make sure super class's are written before current class is written.
1243 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1244 while (SuperClass) {
1245 RewriteInterfaceDecl(SuperClass);
1246 SuperClass = SuperClass->getSuperClass();
1247 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001248 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001249 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001250 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001251 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001252 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1253
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001254 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001255 // Mark this typedef as having been written into its c++ equivalent.
1256 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001257
1258 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001259 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001260 RewriteProperty(*I);
1261 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001262 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001263 I != E; ++I)
1264 RewriteMethodDeclaration(*I);
1265 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001266 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001267 I != E; ++I)
1268 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001269
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001270 // Lastly, comment out the @end.
1271 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1272 "/* @end */");
1273 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001274}
1275
1276Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1277 SourceRange OldRange = PseudoOp->getSourceRange();
1278
1279 // We just magically know some things about the structure of this
1280 // expression.
1281 ObjCMessageExpr *OldMsg =
1282 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1283 PseudoOp->getNumSemanticExprs() - 1));
1284
1285 // Because the rewriter doesn't allow us to rewrite rewritten code,
1286 // we need to suppress rewriting the sub-statements.
1287 Expr *Base, *RHS;
1288 {
1289 DisableReplaceStmtScope S(*this);
1290
1291 // Rebuild the base expression if we have one.
1292 Base = 0;
1293 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1294 Base = OldMsg->getInstanceReceiver();
1295 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1296 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1297 }
1298
1299 // Rebuild the RHS.
1300 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1301 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1302 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1303 }
1304
1305 // TODO: avoid this copy.
1306 SmallVector<SourceLocation, 1> SelLocs;
1307 OldMsg->getSelectorLocs(SelLocs);
1308
1309 ObjCMessageExpr *NewMsg = 0;
1310 switch (OldMsg->getReceiverKind()) {
1311 case ObjCMessageExpr::Class:
1312 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1313 OldMsg->getValueKind(),
1314 OldMsg->getLeftLoc(),
1315 OldMsg->getClassReceiverTypeInfo(),
1316 OldMsg->getSelector(),
1317 SelLocs,
1318 OldMsg->getMethodDecl(),
1319 RHS,
1320 OldMsg->getRightLoc(),
1321 OldMsg->isImplicit());
1322 break;
1323
1324 case ObjCMessageExpr::Instance:
1325 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1326 OldMsg->getValueKind(),
1327 OldMsg->getLeftLoc(),
1328 Base,
1329 OldMsg->getSelector(),
1330 SelLocs,
1331 OldMsg->getMethodDecl(),
1332 RHS,
1333 OldMsg->getRightLoc(),
1334 OldMsg->isImplicit());
1335 break;
1336
1337 case ObjCMessageExpr::SuperClass:
1338 case ObjCMessageExpr::SuperInstance:
1339 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1340 OldMsg->getValueKind(),
1341 OldMsg->getLeftLoc(),
1342 OldMsg->getSuperLoc(),
1343 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1344 OldMsg->getSuperType(),
1345 OldMsg->getSelector(),
1346 SelLocs,
1347 OldMsg->getMethodDecl(),
1348 RHS,
1349 OldMsg->getRightLoc(),
1350 OldMsg->isImplicit());
1351 break;
1352 }
1353
1354 Stmt *Replacement = SynthMessageExpr(NewMsg);
1355 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1356 return Replacement;
1357}
1358
1359Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1360 SourceRange OldRange = PseudoOp->getSourceRange();
1361
1362 // We just magically know some things about the structure of this
1363 // expression.
1364 ObjCMessageExpr *OldMsg =
1365 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1366
1367 // Because the rewriter doesn't allow us to rewrite rewritten code,
1368 // we need to suppress rewriting the sub-statements.
1369 Expr *Base = 0;
1370 {
1371 DisableReplaceStmtScope S(*this);
1372
1373 // Rebuild the base expression if we have one.
1374 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1375 Base = OldMsg->getInstanceReceiver();
1376 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1377 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1378 }
1379 }
1380
1381 // Intentionally empty.
1382 SmallVector<SourceLocation, 1> SelLocs;
1383 SmallVector<Expr*, 1> Args;
1384
1385 ObjCMessageExpr *NewMsg = 0;
1386 switch (OldMsg->getReceiverKind()) {
1387 case ObjCMessageExpr::Class:
1388 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1389 OldMsg->getValueKind(),
1390 OldMsg->getLeftLoc(),
1391 OldMsg->getClassReceiverTypeInfo(),
1392 OldMsg->getSelector(),
1393 SelLocs,
1394 OldMsg->getMethodDecl(),
1395 Args,
1396 OldMsg->getRightLoc(),
1397 OldMsg->isImplicit());
1398 break;
1399
1400 case ObjCMessageExpr::Instance:
1401 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1402 OldMsg->getValueKind(),
1403 OldMsg->getLeftLoc(),
1404 Base,
1405 OldMsg->getSelector(),
1406 SelLocs,
1407 OldMsg->getMethodDecl(),
1408 Args,
1409 OldMsg->getRightLoc(),
1410 OldMsg->isImplicit());
1411 break;
1412
1413 case ObjCMessageExpr::SuperClass:
1414 case ObjCMessageExpr::SuperInstance:
1415 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1416 OldMsg->getValueKind(),
1417 OldMsg->getLeftLoc(),
1418 OldMsg->getSuperLoc(),
1419 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1420 OldMsg->getSuperType(),
1421 OldMsg->getSelector(),
1422 SelLocs,
1423 OldMsg->getMethodDecl(),
1424 Args,
1425 OldMsg->getRightLoc(),
1426 OldMsg->isImplicit());
1427 break;
1428 }
1429
1430 Stmt *Replacement = SynthMessageExpr(NewMsg);
1431 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1432 return Replacement;
1433}
1434
1435/// SynthCountByEnumWithState - To print:
1436/// ((unsigned int (*)
1437/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1438/// (void *)objc_msgSend)((id)l_collection,
1439/// sel_registerName(
1440/// "countByEnumeratingWithState:objects:count:"),
1441/// &enumState,
1442/// (id *)__rw_items, (unsigned int)16)
1443///
1444void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1445 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1446 "id *, unsigned int))(void *)objc_msgSend)";
1447 buf += "\n\t\t";
1448 buf += "((id)l_collection,\n\t\t";
1449 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1450 buf += "\n\t\t";
1451 buf += "&enumState, "
1452 "(id *)__rw_items, (unsigned int)16)";
1453}
1454
1455/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1456/// statement to exit to its outer synthesized loop.
1457///
1458Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1459 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1460 return S;
1461 // replace break with goto __break_label
1462 std::string buf;
1463
1464 SourceLocation startLoc = S->getLocStart();
1465 buf = "goto __break_label_";
1466 buf += utostr(ObjCBcLabelNo.back());
1467 ReplaceText(startLoc, strlen("break"), buf);
1468
1469 return 0;
1470}
1471
1472/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1473/// statement to continue with its inner synthesized loop.
1474///
1475Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1476 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1477 return S;
1478 // replace continue with goto __continue_label
1479 std::string buf;
1480
1481 SourceLocation startLoc = S->getLocStart();
1482 buf = "goto __continue_label_";
1483 buf += utostr(ObjCBcLabelNo.back());
1484 ReplaceText(startLoc, strlen("continue"), buf);
1485
1486 return 0;
1487}
1488
1489/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1490/// It rewrites:
1491/// for ( type elem in collection) { stmts; }
1492
1493/// Into:
1494/// {
1495/// type elem;
1496/// struct __objcFastEnumerationState enumState = { 0 };
1497/// id __rw_items[16];
1498/// id l_collection = (id)collection;
1499/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1500/// objects:__rw_items count:16];
1501/// if (limit) {
1502/// unsigned long startMutations = *enumState.mutationsPtr;
1503/// do {
1504/// unsigned long counter = 0;
1505/// do {
1506/// if (startMutations != *enumState.mutationsPtr)
1507/// objc_enumerationMutation(l_collection);
1508/// elem = (type)enumState.itemsPtr[counter++];
1509/// stmts;
1510/// __continue_label: ;
1511/// } while (counter < limit);
1512/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1513/// objects:__rw_items count:16]);
1514/// elem = nil;
1515/// __break_label: ;
1516/// }
1517/// else
1518/// elem = nil;
1519/// }
1520///
1521Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1522 SourceLocation OrigEnd) {
1523 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1524 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1525 "ObjCForCollectionStmt Statement stack mismatch");
1526 assert(!ObjCBcLabelNo.empty() &&
1527 "ObjCForCollectionStmt - Label No stack empty");
1528
1529 SourceLocation startLoc = S->getLocStart();
1530 const char *startBuf = SM->getCharacterData(startLoc);
1531 StringRef elementName;
1532 std::string elementTypeAsString;
1533 std::string buf;
1534 buf = "\n{\n\t";
1535 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1536 // type elem;
1537 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1538 QualType ElementType = cast<ValueDecl>(D)->getType();
1539 if (ElementType->isObjCQualifiedIdType() ||
1540 ElementType->isObjCQualifiedInterfaceType())
1541 // Simply use 'id' for all qualified types.
1542 elementTypeAsString = "id";
1543 else
1544 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1545 buf += elementTypeAsString;
1546 buf += " ";
1547 elementName = D->getName();
1548 buf += elementName;
1549 buf += ";\n\t";
1550 }
1551 else {
1552 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1553 elementName = DR->getDecl()->getName();
1554 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1555 if (VD->getType()->isObjCQualifiedIdType() ||
1556 VD->getType()->isObjCQualifiedInterfaceType())
1557 // Simply use 'id' for all qualified types.
1558 elementTypeAsString = "id";
1559 else
1560 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1561 }
1562
1563 // struct __objcFastEnumerationState enumState = { 0 };
1564 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1565 // id __rw_items[16];
1566 buf += "id __rw_items[16];\n\t";
1567 // id l_collection = (id)
1568 buf += "id l_collection = (id)";
1569 // Find start location of 'collection' the hard way!
1570 const char *startCollectionBuf = startBuf;
1571 startCollectionBuf += 3; // skip 'for'
1572 startCollectionBuf = strchr(startCollectionBuf, '(');
1573 startCollectionBuf++; // skip '('
1574 // find 'in' and skip it.
1575 while (*startCollectionBuf != ' ' ||
1576 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1577 (*(startCollectionBuf+3) != ' ' &&
1578 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1579 startCollectionBuf++;
1580 startCollectionBuf += 3;
1581
1582 // Replace: "for (type element in" with string constructed thus far.
1583 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1584 // Replace ')' in for '(' type elem in collection ')' with ';'
1585 SourceLocation rightParenLoc = S->getRParenLoc();
1586 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1587 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1588 buf = ";\n\t";
1589
1590 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1591 // objects:__rw_items count:16];
1592 // which is synthesized into:
1593 // unsigned int limit =
1594 // ((unsigned int (*)
1595 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1596 // (void *)objc_msgSend)((id)l_collection,
1597 // sel_registerName(
1598 // "countByEnumeratingWithState:objects:count:"),
1599 // (struct __objcFastEnumerationState *)&state,
1600 // (id *)__rw_items, (unsigned int)16);
1601 buf += "unsigned long limit =\n\t\t";
1602 SynthCountByEnumWithState(buf);
1603 buf += ";\n\t";
1604 /// if (limit) {
1605 /// unsigned long startMutations = *enumState.mutationsPtr;
1606 /// do {
1607 /// unsigned long counter = 0;
1608 /// do {
1609 /// if (startMutations != *enumState.mutationsPtr)
1610 /// objc_enumerationMutation(l_collection);
1611 /// elem = (type)enumState.itemsPtr[counter++];
1612 buf += "if (limit) {\n\t";
1613 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1614 buf += "do {\n\t\t";
1615 buf += "unsigned long counter = 0;\n\t\t";
1616 buf += "do {\n\t\t\t";
1617 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1618 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1619 buf += elementName;
1620 buf += " = (";
1621 buf += elementTypeAsString;
1622 buf += ")enumState.itemsPtr[counter++];";
1623 // Replace ')' in for '(' type elem in collection ')' with all of these.
1624 ReplaceText(lparenLoc, 1, buf);
1625
1626 /// __continue_label: ;
1627 /// } while (counter < limit);
1628 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1629 /// objects:__rw_items count:16]);
1630 /// elem = nil;
1631 /// __break_label: ;
1632 /// }
1633 /// else
1634 /// elem = nil;
1635 /// }
1636 ///
1637 buf = ";\n\t";
1638 buf += "__continue_label_";
1639 buf += utostr(ObjCBcLabelNo.back());
1640 buf += ": ;";
1641 buf += "\n\t\t";
1642 buf += "} while (counter < limit);\n\t";
1643 buf += "} while (limit = ";
1644 SynthCountByEnumWithState(buf);
1645 buf += ");\n\t";
1646 buf += elementName;
1647 buf += " = ((";
1648 buf += elementTypeAsString;
1649 buf += ")0);\n\t";
1650 buf += "__break_label_";
1651 buf += utostr(ObjCBcLabelNo.back());
1652 buf += ": ;\n\t";
1653 buf += "}\n\t";
1654 buf += "else\n\t\t";
1655 buf += elementName;
1656 buf += " = ((";
1657 buf += elementTypeAsString;
1658 buf += ")0);\n\t";
1659 buf += "}\n";
1660
1661 // Insert all these *after* the statement body.
1662 // FIXME: If this should support Obj-C++, support CXXTryStmt
1663 if (isa<CompoundStmt>(S->getBody())) {
1664 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1665 InsertText(endBodyLoc, buf);
1666 } else {
1667 /* Need to treat single statements specially. For example:
1668 *
1669 * for (A *a in b) if (stuff()) break;
1670 * for (A *a in b) xxxyy;
1671 *
1672 * The following code simply scans ahead to the semi to find the actual end.
1673 */
1674 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1675 const char *semiBuf = strchr(stmtBuf, ';');
1676 assert(semiBuf && "Can't find ';'");
1677 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1678 InsertText(endBodyLoc, buf);
1679 }
1680 Stmts.pop_back();
1681 ObjCBcLabelNo.pop_back();
1682 return 0;
1683}
1684
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001685static void Write_RethrowObject(std::string &buf) {
1686 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1687 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1688 buf += "\tid rethrow;\n";
1689 buf += "\t} _fin_force_rethow(_rethrow);";
1690}
1691
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001692/// RewriteObjCSynchronizedStmt -
1693/// This routine rewrites @synchronized(expr) stmt;
1694/// into:
1695/// objc_sync_enter(expr);
1696/// @try stmt @finally { objc_sync_exit(expr); }
1697///
1698Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1699 // Get the start location and compute the semi location.
1700 SourceLocation startLoc = S->getLocStart();
1701 const char *startBuf = SM->getCharacterData(startLoc);
1702
1703 assert((*startBuf == '@') && "bogus @synchronized location");
1704
1705 std::string buf;
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001706 buf = "{ id volatile _rethrow = 0; objc_sync_enter((id)";
1707
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001708 const char *lparenBuf = startBuf;
1709 while (*lparenBuf != '(') lparenBuf++;
1710 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001711 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1712 const char *endBuf = SM->getCharacterData(endLoc);
1713 while (*endBuf != ')') endBuf--;
1714 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1715 buf = ");\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001716 buf += "try ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001717 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001718
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001719 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001720 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1721 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001722
1723 buf = "} catch (id e) {_rethrow = e;}\n";
1724 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001725
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001726 // produce objc_sync_exit(expr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001727 std::string syncBuf;
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001728 syncBuf += "\n\tobjc_sync_exit(";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001729
1730 Expr *syncExpr = S->getSynchExpr();
1731 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1732 ? CK_BitCast :
1733 syncExpr->getType()->isBlockPointerType()
1734 ? CK_BlockPointerToObjCPointerCast
1735 : CK_CPointerToObjCPointerCast;
1736 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1737 CK, syncExpr);
1738 std::string syncExprBufS;
1739 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1740 syncExpr->printPretty(syncExprBuf, *Context, 0,
1741 PrintingPolicy(LangOpts));
1742 syncBuf += syncExprBuf.str();
1743 syncBuf += ");";
1744
1745 buf += syncBuf;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001746 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001747 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001748
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001749 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001750
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001751 return 0;
1752}
1753
1754void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1755{
1756 // Perform a bottom up traversal of all children.
1757 for (Stmt::child_range CI = S->children(); CI; ++CI)
1758 if (*CI)
1759 WarnAboutReturnGotoStmts(*CI);
1760
1761 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1762 Diags.Report(Context->getFullLoc(S->getLocStart()),
1763 TryFinallyContainsReturnDiag);
1764 }
1765 return;
1766}
1767
1768void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1769{
1770 // Perform a bottom up traversal of all children.
1771 for (Stmt::child_range CI = S->children(); CI; ++CI)
1772 if (*CI)
1773 HasReturnStmts(*CI, hasReturns);
1774
1775 if (isa<ReturnStmt>(S))
1776 hasReturns = true;
1777 return;
1778}
1779
1780void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1781 // Perform a bottom up traversal of all children.
1782 for (Stmt::child_range CI = S->children(); CI; ++CI)
1783 if (*CI) {
1784 RewriteTryReturnStmts(*CI);
1785 }
1786 if (isa<ReturnStmt>(S)) {
1787 SourceLocation startLoc = S->getLocStart();
1788 const char *startBuf = SM->getCharacterData(startLoc);
1789
1790 const char *semiBuf = strchr(startBuf, ';');
1791 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1792 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1793
1794 std::string buf;
1795 buf = "{ objc_exception_try_exit(&_stack); return";
1796
1797 ReplaceText(startLoc, 6, buf);
1798 InsertText(onePastSemiLoc, "}");
1799 }
1800 return;
1801}
1802
1803void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1804 // Perform a bottom up traversal of all children.
1805 for (Stmt::child_range CI = S->children(); CI; ++CI)
1806 if (*CI) {
1807 RewriteSyncReturnStmts(*CI, syncExitBuf);
1808 }
1809 if (isa<ReturnStmt>(S)) {
1810 SourceLocation startLoc = S->getLocStart();
1811 const char *startBuf = SM->getCharacterData(startLoc);
1812
1813 const char *semiBuf = strchr(startBuf, ';');
1814 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1815 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1816
1817 std::string buf;
1818 buf = "{ objc_exception_try_exit(&_stack);";
1819 buf += syncExitBuf;
1820 buf += " return";
1821
1822 ReplaceText(startLoc, 6, buf);
1823 InsertText(onePastSemiLoc, "}");
1824 }
1825 return;
1826}
1827
1828Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001829 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001830 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001831 std::string buf;
1832
1833 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001834 if (noCatch)
1835 buf = "{ id volatile _rethrow = 0;\n";
1836 else {
1837 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1838 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001839 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001840 // Get the start location and compute the semi location.
1841 SourceLocation startLoc = S->getLocStart();
1842 const char *startBuf = SM->getCharacterData(startLoc);
1843
1844 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001845 if (finalStmt)
1846 ReplaceText(startLoc, 1, buf);
1847 else
1848 // @try -> try
1849 ReplaceText(startLoc, 1, "");
1850
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001851 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1852 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001853 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001854
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001855 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001856 bool AtRemoved = false;
1857 if (catchDecl) {
1858 QualType t = catchDecl->getType();
1859 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1860 // Should be a pointer to a class.
1861 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1862 if (IDecl) {
1863 std::string Result;
1864 startBuf = SM->getCharacterData(startLoc);
1865 assert((*startBuf == '@') && "bogus @catch location");
1866 SourceLocation rParenLoc = Catch->getRParenLoc();
1867 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1868
1869 // _objc_exc_Foo *_e as argument to catch.
1870 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1871 Result += " *_"; Result += catchDecl->getNameAsString();
1872 Result += ")";
1873 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1874 // Foo *e = (Foo *)_e;
1875 Result.clear();
1876 Result = "{ ";
1877 Result += IDecl->getNameAsString();
1878 Result += " *"; Result += catchDecl->getNameAsString();
1879 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1880 Result += "_"; Result += catchDecl->getNameAsString();
1881
1882 Result += "; ";
1883 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1884 ReplaceText(lBraceLoc, 1, Result);
1885 AtRemoved = true;
1886 }
1887 }
1888 }
1889 if (!AtRemoved)
1890 // @catch -> catch
1891 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001892
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001893 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001894 if (finalStmt) {
1895 buf.clear();
1896 if (noCatch)
1897 buf = "catch (id e) {_rethrow = e;}\n";
1898 else
1899 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1900
1901 SourceLocation startFinalLoc = finalStmt->getLocStart();
1902 ReplaceText(startFinalLoc, 8, buf);
1903 Stmt *body = finalStmt->getFinallyBody();
1904 SourceLocation startFinalBodyLoc = body->getLocStart();
1905 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001906 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001907 ReplaceText(startFinalBodyLoc, 1, buf);
1908
1909 SourceLocation endFinalBodyLoc = body->getLocEnd();
1910 ReplaceText(endFinalBodyLoc, 1, "}\n}");
1911 }
1912
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001913 return 0;
1914}
1915
1916// This can't be done with ReplaceStmt(S, ThrowExpr), since
1917// the throw expression is typically a message expression that's already
1918// been rewritten! (which implies the SourceLocation's are invalid).
1919Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1920 // Get the start location and compute the semi location.
1921 SourceLocation startLoc = S->getLocStart();
1922 const char *startBuf = SM->getCharacterData(startLoc);
1923
1924 assert((*startBuf == '@') && "bogus @throw location");
1925
1926 std::string buf;
1927 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1928 if (S->getThrowExpr())
1929 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001930 else
1931 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001932
1933 // handle "@ throw" correctly.
1934 const char *wBuf = strchr(startBuf, 'w');
1935 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1936 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1937
1938 const char *semiBuf = strchr(startBuf, ';');
1939 assert((*semiBuf == ';') && "@throw: can't find ';'");
1940 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001941 if (S->getThrowExpr())
1942 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001943 return 0;
1944}
1945
1946Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1947 // Create a new string expression.
1948 QualType StrType = Context->getPointerType(Context->CharTy);
1949 std::string StrEncoding;
1950 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1951 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1952 StringLiteral::Ascii, false,
1953 StrType, SourceLocation());
1954 ReplaceStmt(Exp, Replacement);
1955
1956 // Replace this subexpr in the parent.
1957 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1958 return Replacement;
1959}
1960
1961Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1962 if (!SelGetUidFunctionDecl)
1963 SynthSelGetUidFunctionDecl();
1964 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1965 // Create a call to sel_registerName("selName").
1966 SmallVector<Expr*, 8> SelExprs;
1967 QualType argType = Context->getPointerType(Context->CharTy);
1968 SelExprs.push_back(StringLiteral::Create(*Context,
1969 Exp->getSelector().getAsString(),
1970 StringLiteral::Ascii, false,
1971 argType, SourceLocation()));
1972 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1973 &SelExprs[0], SelExprs.size());
1974 ReplaceStmt(Exp, SelExp);
1975 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1976 return SelExp;
1977}
1978
1979CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1980 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1981 SourceLocation EndLoc) {
1982 // Get the type, we will need to reference it in a couple spots.
1983 QualType msgSendType = FD->getType();
1984
1985 // Create a reference to the objc_msgSend() declaration.
1986 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001987 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001988
1989 // Now, we cast the reference to a pointer to the objc_msgSend type.
1990 QualType pToFunc = Context->getPointerType(msgSendType);
1991 ImplicitCastExpr *ICE =
1992 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1993 DRE, 0, VK_RValue);
1994
1995 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1996
1997 CallExpr *Exp =
1998 new (Context) CallExpr(*Context, ICE, args, nargs,
1999 FT->getCallResultType(*Context),
2000 VK_RValue, EndLoc);
2001 return Exp;
2002}
2003
2004static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2005 const char *&startRef, const char *&endRef) {
2006 while (startBuf < endBuf) {
2007 if (*startBuf == '<')
2008 startRef = startBuf; // mark the start.
2009 if (*startBuf == '>') {
2010 if (startRef && *startRef == '<') {
2011 endRef = startBuf; // mark the end.
2012 return true;
2013 }
2014 return false;
2015 }
2016 startBuf++;
2017 }
2018 return false;
2019}
2020
2021static void scanToNextArgument(const char *&argRef) {
2022 int angle = 0;
2023 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2024 if (*argRef == '<')
2025 angle++;
2026 else if (*argRef == '>')
2027 angle--;
2028 argRef++;
2029 }
2030 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2031}
2032
2033bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2034 if (T->isObjCQualifiedIdType())
2035 return true;
2036 if (const PointerType *PT = T->getAs<PointerType>()) {
2037 if (PT->getPointeeType()->isObjCQualifiedIdType())
2038 return true;
2039 }
2040 if (T->isObjCObjectPointerType()) {
2041 T = T->getPointeeType();
2042 return T->isObjCQualifiedInterfaceType();
2043 }
2044 if (T->isArrayType()) {
2045 QualType ElemTy = Context->getBaseElementType(T);
2046 return needToScanForQualifiers(ElemTy);
2047 }
2048 return false;
2049}
2050
2051void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2052 QualType Type = E->getType();
2053 if (needToScanForQualifiers(Type)) {
2054 SourceLocation Loc, EndLoc;
2055
2056 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2057 Loc = ECE->getLParenLoc();
2058 EndLoc = ECE->getRParenLoc();
2059 } else {
2060 Loc = E->getLocStart();
2061 EndLoc = E->getLocEnd();
2062 }
2063 // This will defend against trying to rewrite synthesized expressions.
2064 if (Loc.isInvalid() || EndLoc.isInvalid())
2065 return;
2066
2067 const char *startBuf = SM->getCharacterData(Loc);
2068 const char *endBuf = SM->getCharacterData(EndLoc);
2069 const char *startRef = 0, *endRef = 0;
2070 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2071 // Get the locations of the startRef, endRef.
2072 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2073 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2074 // Comment out the protocol references.
2075 InsertText(LessLoc, "/*");
2076 InsertText(GreaterLoc, "*/");
2077 }
2078 }
2079}
2080
2081void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2082 SourceLocation Loc;
2083 QualType Type;
2084 const FunctionProtoType *proto = 0;
2085 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2086 Loc = VD->getLocation();
2087 Type = VD->getType();
2088 }
2089 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2090 Loc = FD->getLocation();
2091 // Check for ObjC 'id' and class types that have been adorned with protocol
2092 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2093 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2094 assert(funcType && "missing function type");
2095 proto = dyn_cast<FunctionProtoType>(funcType);
2096 if (!proto)
2097 return;
2098 Type = proto->getResultType();
2099 }
2100 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2101 Loc = FD->getLocation();
2102 Type = FD->getType();
2103 }
2104 else
2105 return;
2106
2107 if (needToScanForQualifiers(Type)) {
2108 // Since types are unique, we need to scan the buffer.
2109
2110 const char *endBuf = SM->getCharacterData(Loc);
2111 const char *startBuf = endBuf;
2112 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2113 startBuf--; // scan backward (from the decl location) for return type.
2114 const char *startRef = 0, *endRef = 0;
2115 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2116 // Get the locations of the startRef, endRef.
2117 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2118 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2119 // Comment out the protocol references.
2120 InsertText(LessLoc, "/*");
2121 InsertText(GreaterLoc, "*/");
2122 }
2123 }
2124 if (!proto)
2125 return; // most likely, was a variable
2126 // Now check arguments.
2127 const char *startBuf = SM->getCharacterData(Loc);
2128 const char *startFuncBuf = startBuf;
2129 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2130 if (needToScanForQualifiers(proto->getArgType(i))) {
2131 // Since types are unique, we need to scan the buffer.
2132
2133 const char *endBuf = startBuf;
2134 // scan forward (from the decl location) for argument types.
2135 scanToNextArgument(endBuf);
2136 const char *startRef = 0, *endRef = 0;
2137 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2138 // Get the locations of the startRef, endRef.
2139 SourceLocation LessLoc =
2140 Loc.getLocWithOffset(startRef-startFuncBuf);
2141 SourceLocation GreaterLoc =
2142 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2143 // Comment out the protocol references.
2144 InsertText(LessLoc, "/*");
2145 InsertText(GreaterLoc, "*/");
2146 }
2147 startBuf = ++endBuf;
2148 }
2149 else {
2150 // If the function name is derived from a macro expansion, then the
2151 // argument buffer will not follow the name. Need to speak with Chris.
2152 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2153 startBuf++; // scan forward (from the decl location) for argument types.
2154 startBuf++;
2155 }
2156 }
2157}
2158
2159void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2160 QualType QT = ND->getType();
2161 const Type* TypePtr = QT->getAs<Type>();
2162 if (!isa<TypeOfExprType>(TypePtr))
2163 return;
2164 while (isa<TypeOfExprType>(TypePtr)) {
2165 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2166 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2167 TypePtr = QT->getAs<Type>();
2168 }
2169 // FIXME. This will not work for multiple declarators; as in:
2170 // __typeof__(a) b,c,d;
2171 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2172 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2173 const char *startBuf = SM->getCharacterData(DeclLoc);
2174 if (ND->getInit()) {
2175 std::string Name(ND->getNameAsString());
2176 TypeAsString += " " + Name + " = ";
2177 Expr *E = ND->getInit();
2178 SourceLocation startLoc;
2179 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2180 startLoc = ECE->getLParenLoc();
2181 else
2182 startLoc = E->getLocStart();
2183 startLoc = SM->getExpansionLoc(startLoc);
2184 const char *endBuf = SM->getCharacterData(startLoc);
2185 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2186 }
2187 else {
2188 SourceLocation X = ND->getLocEnd();
2189 X = SM->getExpansionLoc(X);
2190 const char *endBuf = SM->getCharacterData(X);
2191 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2192 }
2193}
2194
2195// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2196void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2197 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2198 SmallVector<QualType, 16> ArgTys;
2199 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2200 QualType getFuncType =
2201 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2202 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2203 SourceLocation(),
2204 SourceLocation(),
2205 SelGetUidIdent, getFuncType, 0,
2206 SC_Extern,
2207 SC_None, false);
2208}
2209
2210void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2211 // declared in <objc/objc.h>
2212 if (FD->getIdentifier() &&
2213 FD->getName() == "sel_registerName") {
2214 SelGetUidFunctionDecl = FD;
2215 return;
2216 }
2217 RewriteObjCQualifiedInterfaceTypes(FD);
2218}
2219
2220void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2221 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2222 const char *argPtr = TypeString.c_str();
2223 if (!strchr(argPtr, '^')) {
2224 Str += TypeString;
2225 return;
2226 }
2227 while (*argPtr) {
2228 Str += (*argPtr == '^' ? '*' : *argPtr);
2229 argPtr++;
2230 }
2231}
2232
2233// FIXME. Consolidate this routine with RewriteBlockPointerType.
2234void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2235 ValueDecl *VD) {
2236 QualType Type = VD->getType();
2237 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2238 const char *argPtr = TypeString.c_str();
2239 int paren = 0;
2240 while (*argPtr) {
2241 switch (*argPtr) {
2242 case '(':
2243 Str += *argPtr;
2244 paren++;
2245 break;
2246 case ')':
2247 Str += *argPtr;
2248 paren--;
2249 break;
2250 case '^':
2251 Str += '*';
2252 if (paren == 1)
2253 Str += VD->getNameAsString();
2254 break;
2255 default:
2256 Str += *argPtr;
2257 break;
2258 }
2259 argPtr++;
2260 }
2261}
2262
2263
2264void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2265 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2266 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2267 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2268 if (!proto)
2269 return;
2270 QualType Type = proto->getResultType();
2271 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2272 FdStr += " ";
2273 FdStr += FD->getName();
2274 FdStr += "(";
2275 unsigned numArgs = proto->getNumArgs();
2276 for (unsigned i = 0; i < numArgs; i++) {
2277 QualType ArgType = proto->getArgType(i);
2278 RewriteBlockPointerType(FdStr, ArgType);
2279 if (i+1 < numArgs)
2280 FdStr += ", ";
2281 }
2282 FdStr += ");\n";
2283 InsertText(FunLocStart, FdStr);
2284 CurFunctionDeclToDeclareForBlock = 0;
2285}
2286
2287// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2288void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2289 if (SuperContructorFunctionDecl)
2290 return;
2291 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2292 SmallVector<QualType, 16> ArgTys;
2293 QualType argT = Context->getObjCIdType();
2294 assert(!argT.isNull() && "Can't find 'id' type");
2295 ArgTys.push_back(argT);
2296 ArgTys.push_back(argT);
2297 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2298 &ArgTys[0], ArgTys.size());
2299 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2300 SourceLocation(),
2301 SourceLocation(),
2302 msgSendIdent, msgSendType, 0,
2303 SC_Extern,
2304 SC_None, false);
2305}
2306
2307// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2308void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2309 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2310 SmallVector<QualType, 16> ArgTys;
2311 QualType argT = Context->getObjCIdType();
2312 assert(!argT.isNull() && "Can't find 'id' type");
2313 ArgTys.push_back(argT);
2314 argT = Context->getObjCSelType();
2315 assert(!argT.isNull() && "Can't find 'SEL' type");
2316 ArgTys.push_back(argT);
2317 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2318 &ArgTys[0], ArgTys.size(),
2319 true /*isVariadic*/);
2320 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2321 SourceLocation(),
2322 SourceLocation(),
2323 msgSendIdent, msgSendType, 0,
2324 SC_Extern,
2325 SC_None, false);
2326}
2327
2328// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2329void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2330 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2331 SmallVector<QualType, 16> ArgTys;
2332 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2333 SourceLocation(), SourceLocation(),
2334 &Context->Idents.get("objc_super"));
2335 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2336 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2337 ArgTys.push_back(argT);
2338 argT = Context->getObjCSelType();
2339 assert(!argT.isNull() && "Can't find 'SEL' type");
2340 ArgTys.push_back(argT);
2341 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2342 &ArgTys[0], ArgTys.size(),
2343 true /*isVariadic*/);
2344 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2345 SourceLocation(),
2346 SourceLocation(),
2347 msgSendIdent, msgSendType, 0,
2348 SC_Extern,
2349 SC_None, false);
2350}
2351
2352// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2353void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2354 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2355 SmallVector<QualType, 16> ArgTys;
2356 QualType argT = Context->getObjCIdType();
2357 assert(!argT.isNull() && "Can't find 'id' type");
2358 ArgTys.push_back(argT);
2359 argT = Context->getObjCSelType();
2360 assert(!argT.isNull() && "Can't find 'SEL' type");
2361 ArgTys.push_back(argT);
2362 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2363 &ArgTys[0], ArgTys.size(),
2364 true /*isVariadic*/);
2365 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2366 SourceLocation(),
2367 SourceLocation(),
2368 msgSendIdent, msgSendType, 0,
2369 SC_Extern,
2370 SC_None, false);
2371}
2372
2373// SynthMsgSendSuperStretFunctionDecl -
2374// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2375void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2376 IdentifierInfo *msgSendIdent =
2377 &Context->Idents.get("objc_msgSendSuper_stret");
2378 SmallVector<QualType, 16> ArgTys;
2379 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2380 SourceLocation(), SourceLocation(),
2381 &Context->Idents.get("objc_super"));
2382 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2383 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2384 ArgTys.push_back(argT);
2385 argT = Context->getObjCSelType();
2386 assert(!argT.isNull() && "Can't find 'SEL' type");
2387 ArgTys.push_back(argT);
2388 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2389 &ArgTys[0], ArgTys.size(),
2390 true /*isVariadic*/);
2391 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2392 SourceLocation(),
2393 SourceLocation(),
2394 msgSendIdent, msgSendType, 0,
2395 SC_Extern,
2396 SC_None, false);
2397}
2398
2399// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2400void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2401 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2402 SmallVector<QualType, 16> ArgTys;
2403 QualType argT = Context->getObjCIdType();
2404 assert(!argT.isNull() && "Can't find 'id' type");
2405 ArgTys.push_back(argT);
2406 argT = Context->getObjCSelType();
2407 assert(!argT.isNull() && "Can't find 'SEL' type");
2408 ArgTys.push_back(argT);
2409 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2410 &ArgTys[0], ArgTys.size(),
2411 true /*isVariadic*/);
2412 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2413 SourceLocation(),
2414 SourceLocation(),
2415 msgSendIdent, msgSendType, 0,
2416 SC_Extern,
2417 SC_None, false);
2418}
2419
2420// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2421void RewriteModernObjC::SynthGetClassFunctionDecl() {
2422 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2423 SmallVector<QualType, 16> ArgTys;
2424 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2425 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2426 &ArgTys[0], ArgTys.size());
2427 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2428 SourceLocation(),
2429 SourceLocation(),
2430 getClassIdent, getClassType, 0,
2431 SC_Extern,
2432 SC_None, false);
2433}
2434
2435// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2436void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2437 IdentifierInfo *getSuperClassIdent =
2438 &Context->Idents.get("class_getSuperclass");
2439 SmallVector<QualType, 16> ArgTys;
2440 ArgTys.push_back(Context->getObjCClassType());
2441 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2442 &ArgTys[0], ArgTys.size());
2443 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2444 SourceLocation(),
2445 SourceLocation(),
2446 getSuperClassIdent,
2447 getClassType, 0,
2448 SC_Extern,
2449 SC_None,
2450 false);
2451}
2452
2453// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2454void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2455 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2456 SmallVector<QualType, 16> ArgTys;
2457 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2458 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2459 &ArgTys[0], ArgTys.size());
2460 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2461 SourceLocation(),
2462 SourceLocation(),
2463 getClassIdent, getClassType, 0,
2464 SC_Extern,
2465 SC_None, false);
2466}
2467
2468Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2469 QualType strType = getConstantStringStructType();
2470
2471 std::string S = "__NSConstantStringImpl_";
2472
2473 std::string tmpName = InFileName;
2474 unsigned i;
2475 for (i=0; i < tmpName.length(); i++) {
2476 char c = tmpName.at(i);
2477 // replace any non alphanumeric characters with '_'.
2478 if (!isalpha(c) && (c < '0' || c > '9'))
2479 tmpName[i] = '_';
2480 }
2481 S += tmpName;
2482 S += "_";
2483 S += utostr(NumObjCStringLiterals++);
2484
2485 Preamble += "static __NSConstantStringImpl " + S;
2486 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2487 Preamble += "0x000007c8,"; // utf8_str
2488 // The pretty printer for StringLiteral handles escape characters properly.
2489 std::string prettyBufS;
2490 llvm::raw_string_ostream prettyBuf(prettyBufS);
2491 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2492 PrintingPolicy(LangOpts));
2493 Preamble += prettyBuf.str();
2494 Preamble += ",";
2495 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2496
2497 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2498 SourceLocation(), &Context->Idents.get(S),
2499 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002500 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002501 SourceLocation());
2502 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2503 Context->getPointerType(DRE->getType()),
2504 VK_RValue, OK_Ordinary,
2505 SourceLocation());
2506 // cast to NSConstantString *
2507 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2508 CK_CPointerToObjCPointerCast, Unop);
2509 ReplaceStmt(Exp, cast);
2510 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2511 return cast;
2512}
2513
2514// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2515QualType RewriteModernObjC::getSuperStructType() {
2516 if (!SuperStructDecl) {
2517 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2518 SourceLocation(), SourceLocation(),
2519 &Context->Idents.get("objc_super"));
2520 QualType FieldTypes[2];
2521
2522 // struct objc_object *receiver;
2523 FieldTypes[0] = Context->getObjCIdType();
2524 // struct objc_class *super;
2525 FieldTypes[1] = Context->getObjCClassType();
2526
2527 // Create fields
2528 for (unsigned i = 0; i < 2; ++i) {
2529 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2530 SourceLocation(),
2531 SourceLocation(), 0,
2532 FieldTypes[i], 0,
2533 /*BitWidth=*/0,
2534 /*Mutable=*/false,
2535 /*HasInit=*/false));
2536 }
2537
2538 SuperStructDecl->completeDefinition();
2539 }
2540 return Context->getTagDeclType(SuperStructDecl);
2541}
2542
2543QualType RewriteModernObjC::getConstantStringStructType() {
2544 if (!ConstantStringDecl) {
2545 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2546 SourceLocation(), SourceLocation(),
2547 &Context->Idents.get("__NSConstantStringImpl"));
2548 QualType FieldTypes[4];
2549
2550 // struct objc_object *receiver;
2551 FieldTypes[0] = Context->getObjCIdType();
2552 // int flags;
2553 FieldTypes[1] = Context->IntTy;
2554 // char *str;
2555 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2556 // long length;
2557 FieldTypes[3] = Context->LongTy;
2558
2559 // Create fields
2560 for (unsigned i = 0; i < 4; ++i) {
2561 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2562 ConstantStringDecl,
2563 SourceLocation(),
2564 SourceLocation(), 0,
2565 FieldTypes[i], 0,
2566 /*BitWidth=*/0,
2567 /*Mutable=*/true,
2568 /*HasInit=*/false));
2569 }
2570
2571 ConstantStringDecl->completeDefinition();
2572 }
2573 return Context->getTagDeclType(ConstantStringDecl);
2574}
2575
2576Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2577 SourceLocation StartLoc,
2578 SourceLocation EndLoc) {
2579 if (!SelGetUidFunctionDecl)
2580 SynthSelGetUidFunctionDecl();
2581 if (!MsgSendFunctionDecl)
2582 SynthMsgSendFunctionDecl();
2583 if (!MsgSendSuperFunctionDecl)
2584 SynthMsgSendSuperFunctionDecl();
2585 if (!MsgSendStretFunctionDecl)
2586 SynthMsgSendStretFunctionDecl();
2587 if (!MsgSendSuperStretFunctionDecl)
2588 SynthMsgSendSuperStretFunctionDecl();
2589 if (!MsgSendFpretFunctionDecl)
2590 SynthMsgSendFpretFunctionDecl();
2591 if (!GetClassFunctionDecl)
2592 SynthGetClassFunctionDecl();
2593 if (!GetSuperClassFunctionDecl)
2594 SynthGetSuperClassFunctionDecl();
2595 if (!GetMetaClassFunctionDecl)
2596 SynthGetMetaClassFunctionDecl();
2597
2598 // default to objc_msgSend().
2599 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2600 // May need to use objc_msgSend_stret() as well.
2601 FunctionDecl *MsgSendStretFlavor = 0;
2602 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2603 QualType resultType = mDecl->getResultType();
2604 if (resultType->isRecordType())
2605 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2606 else if (resultType->isRealFloatingType())
2607 MsgSendFlavor = MsgSendFpretFunctionDecl;
2608 }
2609
2610 // Synthesize a call to objc_msgSend().
2611 SmallVector<Expr*, 8> MsgExprs;
2612 switch (Exp->getReceiverKind()) {
2613 case ObjCMessageExpr::SuperClass: {
2614 MsgSendFlavor = MsgSendSuperFunctionDecl;
2615 if (MsgSendStretFlavor)
2616 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2617 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2618
2619 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2620
2621 SmallVector<Expr*, 4> InitExprs;
2622
2623 // set the receiver to self, the first argument to all methods.
2624 InitExprs.push_back(
2625 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2626 CK_BitCast,
2627 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002628 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002629 Context->getObjCIdType(),
2630 VK_RValue,
2631 SourceLocation()))
2632 ); // set the 'receiver'.
2633
2634 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2635 SmallVector<Expr*, 8> ClsExprs;
2636 QualType argType = Context->getPointerType(Context->CharTy);
2637 ClsExprs.push_back(StringLiteral::Create(*Context,
2638 ClassDecl->getIdentifier()->getName(),
2639 StringLiteral::Ascii, false,
2640 argType, SourceLocation()));
2641 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2642 &ClsExprs[0],
2643 ClsExprs.size(),
2644 StartLoc,
2645 EndLoc);
2646 // (Class)objc_getClass("CurrentClass")
2647 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2648 Context->getObjCClassType(),
2649 CK_BitCast, Cls);
2650 ClsExprs.clear();
2651 ClsExprs.push_back(ArgExpr);
2652 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2653 &ClsExprs[0], ClsExprs.size(),
2654 StartLoc, EndLoc);
2655
2656 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2657 // To turn off a warning, type-cast to 'id'
2658 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2659 NoTypeInfoCStyleCastExpr(Context,
2660 Context->getObjCIdType(),
2661 CK_BitCast, Cls));
2662 // struct objc_super
2663 QualType superType = getSuperStructType();
2664 Expr *SuperRep;
2665
2666 if (LangOpts.MicrosoftExt) {
2667 SynthSuperContructorFunctionDecl();
2668 // Simulate a contructor call...
2669 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002670 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002671 SourceLocation());
2672 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2673 InitExprs.size(),
2674 superType, VK_LValue,
2675 SourceLocation());
2676 // The code for super is a little tricky to prevent collision with
2677 // the structure definition in the header. The rewriter has it's own
2678 // internal definition (__rw_objc_super) that is uses. This is why
2679 // we need the cast below. For example:
2680 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2681 //
2682 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2683 Context->getPointerType(SuperRep->getType()),
2684 VK_RValue, OK_Ordinary,
2685 SourceLocation());
2686 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2687 Context->getPointerType(superType),
2688 CK_BitCast, SuperRep);
2689 } else {
2690 // (struct objc_super) { <exprs from above> }
2691 InitListExpr *ILE =
2692 new (Context) InitListExpr(*Context, SourceLocation(),
2693 &InitExprs[0], InitExprs.size(),
2694 SourceLocation());
2695 TypeSourceInfo *superTInfo
2696 = Context->getTrivialTypeSourceInfo(superType);
2697 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2698 superType, VK_LValue,
2699 ILE, false);
2700 // struct objc_super *
2701 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2702 Context->getPointerType(SuperRep->getType()),
2703 VK_RValue, OK_Ordinary,
2704 SourceLocation());
2705 }
2706 MsgExprs.push_back(SuperRep);
2707 break;
2708 }
2709
2710 case ObjCMessageExpr::Class: {
2711 SmallVector<Expr*, 8> ClsExprs;
2712 QualType argType = Context->getPointerType(Context->CharTy);
2713 ObjCInterfaceDecl *Class
2714 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2715 IdentifierInfo *clsName = Class->getIdentifier();
2716 ClsExprs.push_back(StringLiteral::Create(*Context,
2717 clsName->getName(),
2718 StringLiteral::Ascii, false,
2719 argType, SourceLocation()));
2720 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2721 &ClsExprs[0],
2722 ClsExprs.size(),
2723 StartLoc, EndLoc);
2724 MsgExprs.push_back(Cls);
2725 break;
2726 }
2727
2728 case ObjCMessageExpr::SuperInstance:{
2729 MsgSendFlavor = MsgSendSuperFunctionDecl;
2730 if (MsgSendStretFlavor)
2731 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2732 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2733 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2734 SmallVector<Expr*, 4> InitExprs;
2735
2736 InitExprs.push_back(
2737 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2738 CK_BitCast,
2739 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002740 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002741 Context->getObjCIdType(),
2742 VK_RValue, SourceLocation()))
2743 ); // set the 'receiver'.
2744
2745 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2746 SmallVector<Expr*, 8> ClsExprs;
2747 QualType argType = Context->getPointerType(Context->CharTy);
2748 ClsExprs.push_back(StringLiteral::Create(*Context,
2749 ClassDecl->getIdentifier()->getName(),
2750 StringLiteral::Ascii, false, argType,
2751 SourceLocation()));
2752 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2753 &ClsExprs[0],
2754 ClsExprs.size(),
2755 StartLoc, EndLoc);
2756 // (Class)objc_getClass("CurrentClass")
2757 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2758 Context->getObjCClassType(),
2759 CK_BitCast, Cls);
2760 ClsExprs.clear();
2761 ClsExprs.push_back(ArgExpr);
2762 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2763 &ClsExprs[0], ClsExprs.size(),
2764 StartLoc, EndLoc);
2765
2766 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2767 // To turn off a warning, type-cast to 'id'
2768 InitExprs.push_back(
2769 // set 'super class', using class_getSuperclass().
2770 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2771 CK_BitCast, Cls));
2772 // struct objc_super
2773 QualType superType = getSuperStructType();
2774 Expr *SuperRep;
2775
2776 if (LangOpts.MicrosoftExt) {
2777 SynthSuperContructorFunctionDecl();
2778 // Simulate a contructor call...
2779 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002780 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002781 SourceLocation());
2782 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2783 InitExprs.size(),
2784 superType, VK_LValue, SourceLocation());
2785 // The code for super is a little tricky to prevent collision with
2786 // the structure definition in the header. The rewriter has it's own
2787 // internal definition (__rw_objc_super) that is uses. This is why
2788 // we need the cast below. For example:
2789 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2790 //
2791 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2792 Context->getPointerType(SuperRep->getType()),
2793 VK_RValue, OK_Ordinary,
2794 SourceLocation());
2795 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2796 Context->getPointerType(superType),
2797 CK_BitCast, SuperRep);
2798 } else {
2799 // (struct objc_super) { <exprs from above> }
2800 InitListExpr *ILE =
2801 new (Context) InitListExpr(*Context, SourceLocation(),
2802 &InitExprs[0], InitExprs.size(),
2803 SourceLocation());
2804 TypeSourceInfo *superTInfo
2805 = Context->getTrivialTypeSourceInfo(superType);
2806 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2807 superType, VK_RValue, ILE,
2808 false);
2809 }
2810 MsgExprs.push_back(SuperRep);
2811 break;
2812 }
2813
2814 case ObjCMessageExpr::Instance: {
2815 // Remove all type-casts because it may contain objc-style types; e.g.
2816 // Foo<Proto> *.
2817 Expr *recExpr = Exp->getInstanceReceiver();
2818 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2819 recExpr = CE->getSubExpr();
2820 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2821 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2822 ? CK_BlockPointerToObjCPointerCast
2823 : CK_CPointerToObjCPointerCast;
2824
2825 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2826 CK, recExpr);
2827 MsgExprs.push_back(recExpr);
2828 break;
2829 }
2830 }
2831
2832 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2833 SmallVector<Expr*, 8> SelExprs;
2834 QualType argType = Context->getPointerType(Context->CharTy);
2835 SelExprs.push_back(StringLiteral::Create(*Context,
2836 Exp->getSelector().getAsString(),
2837 StringLiteral::Ascii, false,
2838 argType, SourceLocation()));
2839 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2840 &SelExprs[0], SelExprs.size(),
2841 StartLoc,
2842 EndLoc);
2843 MsgExprs.push_back(SelExp);
2844
2845 // Now push any user supplied arguments.
2846 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2847 Expr *userExpr = Exp->getArg(i);
2848 // Make all implicit casts explicit...ICE comes in handy:-)
2849 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2850 // Reuse the ICE type, it is exactly what the doctor ordered.
2851 QualType type = ICE->getType();
2852 if (needToScanForQualifiers(type))
2853 type = Context->getObjCIdType();
2854 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2855 (void)convertBlockPointerToFunctionPointer(type);
2856 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2857 CastKind CK;
2858 if (SubExpr->getType()->isIntegralType(*Context) &&
2859 type->isBooleanType()) {
2860 CK = CK_IntegralToBoolean;
2861 } else if (type->isObjCObjectPointerType()) {
2862 if (SubExpr->getType()->isBlockPointerType()) {
2863 CK = CK_BlockPointerToObjCPointerCast;
2864 } else if (SubExpr->getType()->isPointerType()) {
2865 CK = CK_CPointerToObjCPointerCast;
2866 } else {
2867 CK = CK_BitCast;
2868 }
2869 } else {
2870 CK = CK_BitCast;
2871 }
2872
2873 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2874 }
2875 // Make id<P...> cast into an 'id' cast.
2876 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2877 if (CE->getType()->isObjCQualifiedIdType()) {
2878 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2879 userExpr = CE->getSubExpr();
2880 CastKind CK;
2881 if (userExpr->getType()->isIntegralType(*Context)) {
2882 CK = CK_IntegralToPointer;
2883 } else if (userExpr->getType()->isBlockPointerType()) {
2884 CK = CK_BlockPointerToObjCPointerCast;
2885 } else if (userExpr->getType()->isPointerType()) {
2886 CK = CK_CPointerToObjCPointerCast;
2887 } else {
2888 CK = CK_BitCast;
2889 }
2890 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2891 CK, userExpr);
2892 }
2893 }
2894 MsgExprs.push_back(userExpr);
2895 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2896 // out the argument in the original expression (since we aren't deleting
2897 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2898 //Exp->setArg(i, 0);
2899 }
2900 // Generate the funky cast.
2901 CastExpr *cast;
2902 SmallVector<QualType, 8> ArgTypes;
2903 QualType returnType;
2904
2905 // Push 'id' and 'SEL', the 2 implicit arguments.
2906 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2907 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2908 else
2909 ArgTypes.push_back(Context->getObjCIdType());
2910 ArgTypes.push_back(Context->getObjCSelType());
2911 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2912 // Push any user argument types.
2913 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2914 E = OMD->param_end(); PI != E; ++PI) {
2915 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2916 ? Context->getObjCIdType()
2917 : (*PI)->getType();
2918 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2919 (void)convertBlockPointerToFunctionPointer(t);
2920 ArgTypes.push_back(t);
2921 }
2922 returnType = Exp->getType();
2923 convertToUnqualifiedObjCType(returnType);
2924 (void)convertBlockPointerToFunctionPointer(returnType);
2925 } else {
2926 returnType = Context->getObjCIdType();
2927 }
2928 // Get the type, we will need to reference it in a couple spots.
2929 QualType msgSendType = MsgSendFlavor->getType();
2930
2931 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002932 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002933 VK_LValue, SourceLocation());
2934
2935 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2936 // If we don't do this cast, we get the following bizarre warning/note:
2937 // xx.m:13: warning: function called through a non-compatible type
2938 // xx.m:13: note: if this code is reached, the program will abort
2939 cast = NoTypeInfoCStyleCastExpr(Context,
2940 Context->getPointerType(Context->VoidTy),
2941 CK_BitCast, DRE);
2942
2943 // Now do the "normal" pointer to function cast.
2944 QualType castType =
2945 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2946 // If we don't have a method decl, force a variadic cast.
2947 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2948 castType = Context->getPointerType(castType);
2949 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2950 cast);
2951
2952 // Don't forget the parens to enforce the proper binding.
2953 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2954
2955 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2956 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2957 MsgExprs.size(),
2958 FT->getResultType(), VK_RValue,
2959 EndLoc);
2960 Stmt *ReplacingStmt = CE;
2961 if (MsgSendStretFlavor) {
2962 // We have the method which returns a struct/union. Must also generate
2963 // call to objc_msgSend_stret and hang both varieties on a conditional
2964 // expression which dictate which one to envoke depending on size of
2965 // method's return type.
2966
2967 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002968 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2969 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002970 VK_LValue, SourceLocation());
2971 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2972 cast = NoTypeInfoCStyleCastExpr(Context,
2973 Context->getPointerType(Context->VoidTy),
2974 CK_BitCast, STDRE);
2975 // Now do the "normal" pointer to function cast.
2976 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2977 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2978 castType = Context->getPointerType(castType);
2979 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2980 cast);
2981
2982 // Don't forget the parens to enforce the proper binding.
2983 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2984
2985 FT = msgSendType->getAs<FunctionType>();
2986 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2987 MsgExprs.size(),
2988 FT->getResultType(), VK_RValue,
2989 SourceLocation());
2990
2991 // Build sizeof(returnType)
2992 UnaryExprOrTypeTraitExpr *sizeofExpr =
2993 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2994 Context->getTrivialTypeSourceInfo(returnType),
2995 Context->getSizeType(), SourceLocation(),
2996 SourceLocation());
2997 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2998 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2999 // For X86 it is more complicated and some kind of target specific routine
3000 // is needed to decide what to do.
3001 unsigned IntSize =
3002 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3003 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3004 llvm::APInt(IntSize, 8),
3005 Context->IntTy,
3006 SourceLocation());
3007 BinaryOperator *lessThanExpr =
3008 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3009 VK_RValue, OK_Ordinary, SourceLocation());
3010 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3011 ConditionalOperator *CondExpr =
3012 new (Context) ConditionalOperator(lessThanExpr,
3013 SourceLocation(), CE,
3014 SourceLocation(), STCE,
3015 returnType, VK_RValue, OK_Ordinary);
3016 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3017 CondExpr);
3018 }
3019 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3020 return ReplacingStmt;
3021}
3022
3023Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3024 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3025 Exp->getLocEnd());
3026
3027 // Now do the actual rewrite.
3028 ReplaceStmt(Exp, ReplacingStmt);
3029
3030 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3031 return ReplacingStmt;
3032}
3033
3034// typedef struct objc_object Protocol;
3035QualType RewriteModernObjC::getProtocolType() {
3036 if (!ProtocolTypeDecl) {
3037 TypeSourceInfo *TInfo
3038 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3039 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3040 SourceLocation(), SourceLocation(),
3041 &Context->Idents.get("Protocol"),
3042 TInfo);
3043 }
3044 return Context->getTypeDeclType(ProtocolTypeDecl);
3045}
3046
3047/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3048/// a synthesized/forward data reference (to the protocol's metadata).
3049/// The forward references (and metadata) are generated in
3050/// RewriteModernObjC::HandleTranslationUnit().
3051Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003052 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3053 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003054 IdentifierInfo *ID = &Context->Idents.get(Name);
3055 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3056 SourceLocation(), ID, getProtocolType(), 0,
3057 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003058 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3059 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003060 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3061 Context->getPointerType(DRE->getType()),
3062 VK_RValue, OK_Ordinary, SourceLocation());
3063 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3064 CK_BitCast,
3065 DerefExpr);
3066 ReplaceStmt(Exp, castExpr);
3067 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3068 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3069 return castExpr;
3070
3071}
3072
3073bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3074 const char *endBuf) {
3075 while (startBuf < endBuf) {
3076 if (*startBuf == '#') {
3077 // Skip whitespace.
3078 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3079 ;
3080 if (!strncmp(startBuf, "if", strlen("if")) ||
3081 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3082 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3083 !strncmp(startBuf, "define", strlen("define")) ||
3084 !strncmp(startBuf, "undef", strlen("undef")) ||
3085 !strncmp(startBuf, "else", strlen("else")) ||
3086 !strncmp(startBuf, "elif", strlen("elif")) ||
3087 !strncmp(startBuf, "endif", strlen("endif")) ||
3088 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3089 !strncmp(startBuf, "include", strlen("include")) ||
3090 !strncmp(startBuf, "import", strlen("import")) ||
3091 !strncmp(startBuf, "include_next", strlen("include_next")))
3092 return true;
3093 }
3094 startBuf++;
3095 }
3096 return false;
3097}
3098
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003099/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003100/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003101bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3102 std::string &Result) {
3103 if (Type->isArrayType()) {
3104 QualType ElemTy = Context->getBaseElementType(Type);
3105 return RewriteObjCFieldDeclType(ElemTy, Result);
3106 }
3107 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003108 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3109 if (RD->isCompleteDefinition()) {
3110 if (RD->isStruct())
3111 Result += "\n\tstruct ";
3112 else if (RD->isUnion())
3113 Result += "\n\tunion ";
3114 else
3115 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003116
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003117 Result += RD->getName();
3118 if (TagsDefinedInIvarDecls.count(RD)) {
3119 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003120 Result += " ";
3121 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003122 }
3123 TagsDefinedInIvarDecls.insert(RD);
3124 Result += " {\n";
3125 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003126 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003127 FieldDecl *FD = *i;
3128 RewriteObjCFieldDecl(FD, Result);
3129 }
3130 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003131 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003132 }
3133 }
3134 else if (Type->isEnumeralType()) {
3135 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3136 if (ED->isCompleteDefinition()) {
3137 Result += "\n\tenum ";
3138 Result += ED->getName();
3139 if (TagsDefinedInIvarDecls.count(ED)) {
3140 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003141 Result += " ";
3142 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003143 }
3144 TagsDefinedInIvarDecls.insert(ED);
3145
3146 Result += " {\n";
3147 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3148 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3149 Result += "\t"; Result += EC->getName(); Result += " = ";
3150 llvm::APSInt Val = EC->getInitVal();
3151 Result += Val.toString(10);
3152 Result += ",\n";
3153 }
3154 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003155 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003156 }
3157 }
3158
3159 Result += "\t";
3160 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003161 return false;
3162}
3163
3164
3165/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3166/// It handles elaborated types, as well as enum types in the process.
3167void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3168 std::string &Result) {
3169 QualType Type = fieldDecl->getType();
3170 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003171
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003172 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3173 if (!EleboratedType)
3174 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003175 Result += Name;
3176 if (fieldDecl->isBitField()) {
3177 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3178 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003179 else if (EleboratedType && Type->isArrayType()) {
3180 CanQualType CType = Context->getCanonicalType(Type);
3181 while (isa<ArrayType>(CType)) {
3182 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3183 Result += "[";
3184 llvm::APInt Dim = CAT->getSize();
3185 Result += utostr(Dim.getZExtValue());
3186 Result += "]";
3187 }
3188 CType = CType->getAs<ArrayType>()->getElementType();
3189 }
3190 }
3191
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003192 Result += ";\n";
3193}
3194
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003195/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3196/// an objective-c class with ivars.
3197void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3198 std::string &Result) {
3199 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3200 assert(CDecl->getName() != "" &&
3201 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003202 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003203 SmallVector<ObjCIvarDecl *, 8> IVars;
3204 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003205 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003206 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003207
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003208 SourceLocation LocStart = CDecl->getLocStart();
3209 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003210
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003211 const char *startBuf = SM->getCharacterData(LocStart);
3212 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003213
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003214 // If no ivars and no root or if its root, directly or indirectly,
3215 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003216 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003217 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3218 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3219 ReplaceText(LocStart, endBuf-startBuf, Result);
3220 return;
3221 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003222
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003223 Result += "\nstruct ";
3224 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003225 Result += "_IMPL {\n";
3226
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003227 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003228 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3229 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3230 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003231 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003232 TagsDefinedInIvarDecls.clear();
3233 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3234 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003235
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003236 Result += "};\n";
3237 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3238 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003239 // Mark this struct as having been generated.
3240 if (!ObjCSynthesizedStructs.insert(CDecl))
3241 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003242}
3243
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003244/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3245/// have been referenced in an ivar access expression.
3246void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3247 std::string &Result) {
3248 // write out ivar offset symbols which have been referenced in an ivar
3249 // access expression.
3250 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3251 if (Ivars.empty())
3252 return;
3253 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3254 e = Ivars.end(); i != e; i++) {
3255 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003256 Result += "\n";
3257 if (LangOpts.MicrosoftExt)
3258 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3259 if (LangOpts.MicrosoftExt &&
3260 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3261 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3262 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3263 if (CDecl->getImplementation())
3264 Result += "__declspec(dllexport) ";
3265 }
3266 Result += "extern unsigned long OBJC_IVAR_$_";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003267 Result += CDecl->getName(); Result += "_";
3268 Result += IvarDecl->getName(); Result += ";";
3269 }
3270}
3271
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003272//===----------------------------------------------------------------------===//
3273// Meta Data Emission
3274//===----------------------------------------------------------------------===//
3275
3276
3277/// RewriteImplementations - This routine rewrites all method implementations
3278/// and emits meta-data.
3279
3280void RewriteModernObjC::RewriteImplementations() {
3281 int ClsDefCount = ClassImplementation.size();
3282 int CatDefCount = CategoryImplementation.size();
3283
3284 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003285 for (int i = 0; i < ClsDefCount; i++) {
3286 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3287 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3288 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003289 assert(false &&
3290 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003291 RewriteImplementationDecl(OIMP);
3292 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003293
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003294 for (int i = 0; i < CatDefCount; i++) {
3295 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3296 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3297 if (CDecl->isImplicitInterfaceDecl())
3298 assert(false &&
3299 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003300 RewriteImplementationDecl(CIMP);
3301 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003302}
3303
3304void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3305 const std::string &Name,
3306 ValueDecl *VD, bool def) {
3307 assert(BlockByRefDeclNo.count(VD) &&
3308 "RewriteByRefString: ByRef decl missing");
3309 if (def)
3310 ResultStr += "struct ";
3311 ResultStr += "__Block_byref_" + Name +
3312 "_" + utostr(BlockByRefDeclNo[VD]) ;
3313}
3314
3315static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3316 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3317 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3318 return false;
3319}
3320
3321std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3322 StringRef funcName,
3323 std::string Tag) {
3324 const FunctionType *AFT = CE->getFunctionType();
3325 QualType RT = AFT->getResultType();
3326 std::string StructRef = "struct " + Tag;
3327 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3328 funcName.str() + "_" + "block_func_" + utostr(i);
3329
3330 BlockDecl *BD = CE->getBlockDecl();
3331
3332 if (isa<FunctionNoProtoType>(AFT)) {
3333 // No user-supplied arguments. Still need to pass in a pointer to the
3334 // block (to reference imported block decl refs).
3335 S += "(" + StructRef + " *__cself)";
3336 } else if (BD->param_empty()) {
3337 S += "(" + StructRef + " *__cself)";
3338 } else {
3339 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3340 assert(FT && "SynthesizeBlockFunc: No function proto");
3341 S += '(';
3342 // first add the implicit argument.
3343 S += StructRef + " *__cself, ";
3344 std::string ParamStr;
3345 for (BlockDecl::param_iterator AI = BD->param_begin(),
3346 E = BD->param_end(); AI != E; ++AI) {
3347 if (AI != BD->param_begin()) S += ", ";
3348 ParamStr = (*AI)->getNameAsString();
3349 QualType QT = (*AI)->getType();
3350 if (convertBlockPointerToFunctionPointer(QT))
3351 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3352 else
3353 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3354 S += ParamStr;
3355 }
3356 if (FT->isVariadic()) {
3357 if (!BD->param_empty()) S += ", ";
3358 S += "...";
3359 }
3360 S += ')';
3361 }
3362 S += " {\n";
3363
3364 // Create local declarations to avoid rewriting all closure decl ref exprs.
3365 // First, emit a declaration for all "by ref" decls.
3366 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3367 E = BlockByRefDecls.end(); I != E; ++I) {
3368 S += " ";
3369 std::string Name = (*I)->getNameAsString();
3370 std::string TypeString;
3371 RewriteByRefString(TypeString, Name, (*I));
3372 TypeString += " *";
3373 Name = TypeString + Name;
3374 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3375 }
3376 // Next, emit a declaration for all "by copy" declarations.
3377 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3378 E = BlockByCopyDecls.end(); I != E; ++I) {
3379 S += " ";
3380 // Handle nested closure invocation. For example:
3381 //
3382 // void (^myImportedClosure)(void);
3383 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3384 //
3385 // void (^anotherClosure)(void);
3386 // anotherClosure = ^(void) {
3387 // myImportedClosure(); // import and invoke the closure
3388 // };
3389 //
3390 if (isTopLevelBlockPointerType((*I)->getType())) {
3391 RewriteBlockPointerTypeVariable(S, (*I));
3392 S += " = (";
3393 RewriteBlockPointerType(S, (*I)->getType());
3394 S += ")";
3395 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3396 }
3397 else {
3398 std::string Name = (*I)->getNameAsString();
3399 QualType QT = (*I)->getType();
3400 if (HasLocalVariableExternalStorage(*I))
3401 QT = Context->getPointerType(QT);
3402 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3403 S += Name + " = __cself->" +
3404 (*I)->getNameAsString() + "; // bound by copy\n";
3405 }
3406 }
3407 std::string RewrittenStr = RewrittenBlockExprs[CE];
3408 const char *cstr = RewrittenStr.c_str();
3409 while (*cstr++ != '{') ;
3410 S += cstr;
3411 S += "\n";
3412 return S;
3413}
3414
3415std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3416 StringRef funcName,
3417 std::string Tag) {
3418 std::string StructRef = "struct " + Tag;
3419 std::string S = "static void __";
3420
3421 S += funcName;
3422 S += "_block_copy_" + utostr(i);
3423 S += "(" + StructRef;
3424 S += "*dst, " + StructRef;
3425 S += "*src) {";
3426 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3427 E = ImportedBlockDecls.end(); I != E; ++I) {
3428 ValueDecl *VD = (*I);
3429 S += "_Block_object_assign((void*)&dst->";
3430 S += (*I)->getNameAsString();
3431 S += ", (void*)src->";
3432 S += (*I)->getNameAsString();
3433 if (BlockByRefDeclsPtrSet.count((*I)))
3434 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3435 else if (VD->getType()->isBlockPointerType())
3436 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3437 else
3438 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3439 }
3440 S += "}\n";
3441
3442 S += "\nstatic void __";
3443 S += funcName;
3444 S += "_block_dispose_" + utostr(i);
3445 S += "(" + StructRef;
3446 S += "*src) {";
3447 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3448 E = ImportedBlockDecls.end(); I != E; ++I) {
3449 ValueDecl *VD = (*I);
3450 S += "_Block_object_dispose((void*)src->";
3451 S += (*I)->getNameAsString();
3452 if (BlockByRefDeclsPtrSet.count((*I)))
3453 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3454 else if (VD->getType()->isBlockPointerType())
3455 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3456 else
3457 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3458 }
3459 S += "}\n";
3460 return S;
3461}
3462
3463std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3464 std::string Desc) {
3465 std::string S = "\nstruct " + Tag;
3466 std::string Constructor = " " + Tag;
3467
3468 S += " {\n struct __block_impl impl;\n";
3469 S += " struct " + Desc;
3470 S += "* Desc;\n";
3471
3472 Constructor += "(void *fp, "; // Invoke function pointer.
3473 Constructor += "struct " + Desc; // Descriptor pointer.
3474 Constructor += " *desc";
3475
3476 if (BlockDeclRefs.size()) {
3477 // Output all "by copy" declarations.
3478 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3479 E = BlockByCopyDecls.end(); I != E; ++I) {
3480 S += " ";
3481 std::string FieldName = (*I)->getNameAsString();
3482 std::string ArgName = "_" + FieldName;
3483 // Handle nested closure invocation. For example:
3484 //
3485 // void (^myImportedBlock)(void);
3486 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3487 //
3488 // void (^anotherBlock)(void);
3489 // anotherBlock = ^(void) {
3490 // myImportedBlock(); // import and invoke the closure
3491 // };
3492 //
3493 if (isTopLevelBlockPointerType((*I)->getType())) {
3494 S += "struct __block_impl *";
3495 Constructor += ", void *" + ArgName;
3496 } else {
3497 QualType QT = (*I)->getType();
3498 if (HasLocalVariableExternalStorage(*I))
3499 QT = Context->getPointerType(QT);
3500 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3501 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3502 Constructor += ", " + ArgName;
3503 }
3504 S += FieldName + ";\n";
3505 }
3506 // Output all "by ref" declarations.
3507 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3508 E = BlockByRefDecls.end(); I != E; ++I) {
3509 S += " ";
3510 std::string FieldName = (*I)->getNameAsString();
3511 std::string ArgName = "_" + FieldName;
3512 {
3513 std::string TypeString;
3514 RewriteByRefString(TypeString, FieldName, (*I));
3515 TypeString += " *";
3516 FieldName = TypeString + FieldName;
3517 ArgName = TypeString + ArgName;
3518 Constructor += ", " + ArgName;
3519 }
3520 S += FieldName + "; // by ref\n";
3521 }
3522 // Finish writing the constructor.
3523 Constructor += ", int flags=0)";
3524 // Initialize all "by copy" arguments.
3525 bool firsTime = true;
3526 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3527 E = BlockByCopyDecls.end(); I != E; ++I) {
3528 std::string Name = (*I)->getNameAsString();
3529 if (firsTime) {
3530 Constructor += " : ";
3531 firsTime = false;
3532 }
3533 else
3534 Constructor += ", ";
3535 if (isTopLevelBlockPointerType((*I)->getType()))
3536 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3537 else
3538 Constructor += Name + "(_" + Name + ")";
3539 }
3540 // Initialize all "by ref" arguments.
3541 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3542 E = BlockByRefDecls.end(); I != E; ++I) {
3543 std::string Name = (*I)->getNameAsString();
3544 if (firsTime) {
3545 Constructor += " : ";
3546 firsTime = false;
3547 }
3548 else
3549 Constructor += ", ";
3550 Constructor += Name + "(_" + Name + "->__forwarding)";
3551 }
3552
3553 Constructor += " {\n";
3554 if (GlobalVarDecl)
3555 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3556 else
3557 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3558 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3559
3560 Constructor += " Desc = desc;\n";
3561 } else {
3562 // Finish writing the constructor.
3563 Constructor += ", int flags=0) {\n";
3564 if (GlobalVarDecl)
3565 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3566 else
3567 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3568 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3569 Constructor += " Desc = desc;\n";
3570 }
3571 Constructor += " ";
3572 Constructor += "}\n";
3573 S += Constructor;
3574 S += "};\n";
3575 return S;
3576}
3577
3578std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3579 std::string ImplTag, int i,
3580 StringRef FunName,
3581 unsigned hasCopy) {
3582 std::string S = "\nstatic struct " + DescTag;
3583
3584 S += " {\n unsigned long reserved;\n";
3585 S += " unsigned long Block_size;\n";
3586 if (hasCopy) {
3587 S += " void (*copy)(struct ";
3588 S += ImplTag; S += "*, struct ";
3589 S += ImplTag; S += "*);\n";
3590
3591 S += " void (*dispose)(struct ";
3592 S += ImplTag; S += "*);\n";
3593 }
3594 S += "} ";
3595
3596 S += DescTag + "_DATA = { 0, sizeof(struct ";
3597 S += ImplTag + ")";
3598 if (hasCopy) {
3599 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3600 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3601 }
3602 S += "};\n";
3603 return S;
3604}
3605
3606void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3607 StringRef FunName) {
3608 // Insert declaration for the function in which block literal is used.
3609 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3610 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3611 bool RewriteSC = (GlobalVarDecl &&
3612 !Blocks.empty() &&
3613 GlobalVarDecl->getStorageClass() == SC_Static &&
3614 GlobalVarDecl->getType().getCVRQualifiers());
3615 if (RewriteSC) {
3616 std::string SC(" void __");
3617 SC += GlobalVarDecl->getNameAsString();
3618 SC += "() {}";
3619 InsertText(FunLocStart, SC);
3620 }
3621
3622 // Insert closures that were part of the function.
3623 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3624 CollectBlockDeclRefInfo(Blocks[i]);
3625 // Need to copy-in the inner copied-in variables not actually used in this
3626 // block.
3627 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003628 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003629 ValueDecl *VD = Exp->getDecl();
3630 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003631 if (!VD->hasAttr<BlocksAttr>()) {
3632 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3633 BlockByCopyDeclsPtrSet.insert(VD);
3634 BlockByCopyDecls.push_back(VD);
3635 }
3636 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003637 }
John McCallf4b88a42012-03-10 09:33:50 +00003638
3639 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003640 BlockByRefDeclsPtrSet.insert(VD);
3641 BlockByRefDecls.push_back(VD);
3642 }
John McCallf4b88a42012-03-10 09:33:50 +00003643
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003644 // imported objects in the inner blocks not used in the outer
3645 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003646 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003647 VD->getType()->isBlockPointerType())
3648 ImportedBlockDecls.insert(VD);
3649 }
3650
3651 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3652 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3653
3654 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3655
3656 InsertText(FunLocStart, CI);
3657
3658 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3659
3660 InsertText(FunLocStart, CF);
3661
3662 if (ImportedBlockDecls.size()) {
3663 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3664 InsertText(FunLocStart, HF);
3665 }
3666 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3667 ImportedBlockDecls.size() > 0);
3668 InsertText(FunLocStart, BD);
3669
3670 BlockDeclRefs.clear();
3671 BlockByRefDecls.clear();
3672 BlockByRefDeclsPtrSet.clear();
3673 BlockByCopyDecls.clear();
3674 BlockByCopyDeclsPtrSet.clear();
3675 ImportedBlockDecls.clear();
3676 }
3677 if (RewriteSC) {
3678 // Must insert any 'const/volatile/static here. Since it has been
3679 // removed as result of rewriting of block literals.
3680 std::string SC;
3681 if (GlobalVarDecl->getStorageClass() == SC_Static)
3682 SC = "static ";
3683 if (GlobalVarDecl->getType().isConstQualified())
3684 SC += "const ";
3685 if (GlobalVarDecl->getType().isVolatileQualified())
3686 SC += "volatile ";
3687 if (GlobalVarDecl->getType().isRestrictQualified())
3688 SC += "restrict ";
3689 InsertText(FunLocStart, SC);
3690 }
3691
3692 Blocks.clear();
3693 InnerDeclRefsCount.clear();
3694 InnerDeclRefs.clear();
3695 RewrittenBlockExprs.clear();
3696}
3697
3698void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3699 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3700 StringRef FuncName = FD->getName();
3701
3702 SynthesizeBlockLiterals(FunLocStart, FuncName);
3703}
3704
3705static void BuildUniqueMethodName(std::string &Name,
3706 ObjCMethodDecl *MD) {
3707 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3708 Name = IFace->getName();
3709 Name += "__" + MD->getSelector().getAsString();
3710 // Convert colons to underscores.
3711 std::string::size_type loc = 0;
3712 while ((loc = Name.find(":", loc)) != std::string::npos)
3713 Name.replace(loc, 1, "_");
3714}
3715
3716void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3717 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3718 //SourceLocation FunLocStart = MD->getLocStart();
3719 SourceLocation FunLocStart = MD->getLocStart();
3720 std::string FuncName;
3721 BuildUniqueMethodName(FuncName, MD);
3722 SynthesizeBlockLiterals(FunLocStart, FuncName);
3723}
3724
3725void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3726 for (Stmt::child_range CI = S->children(); CI; ++CI)
3727 if (*CI) {
3728 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3729 GetBlockDeclRefExprs(CBE->getBody());
3730 else
3731 GetBlockDeclRefExprs(*CI);
3732 }
3733 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003734 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3735 if (DRE->refersToEnclosingLocal() &&
3736 HasLocalVariableExternalStorage(DRE->getDecl())) {
3737 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003738 }
3739
3740 return;
3741}
3742
3743void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003744 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003745 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3746 for (Stmt::child_range CI = S->children(); CI; ++CI)
3747 if (*CI) {
3748 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3749 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3750 GetInnerBlockDeclRefExprs(CBE->getBody(),
3751 InnerBlockDeclRefs,
3752 InnerContexts);
3753 }
3754 else
3755 GetInnerBlockDeclRefExprs(*CI,
3756 InnerBlockDeclRefs,
3757 InnerContexts);
3758
3759 }
3760 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003761 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3762 if (DRE->refersToEnclosingLocal()) {
3763 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3764 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3765 InnerBlockDeclRefs.push_back(DRE);
3766 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3767 if (Var->isFunctionOrMethodVarDecl())
3768 ImportedLocalExternalDecls.insert(Var);
3769 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003770 }
3771
3772 return;
3773}
3774
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003775/// convertObjCTypeToCStyleType - This routine converts such objc types
3776/// as qualified objects, and blocks to their closest c/c++ types that
3777/// it can. It returns true if input type was modified.
3778bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3779 QualType oldT = T;
3780 convertBlockPointerToFunctionPointer(T);
3781 if (T->isFunctionPointerType()) {
3782 QualType PointeeTy;
3783 if (const PointerType* PT = T->getAs<PointerType>()) {
3784 PointeeTy = PT->getPointeeType();
3785 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3786 T = convertFunctionTypeOfBlocks(FT);
3787 T = Context->getPointerType(T);
3788 }
3789 }
3790 }
3791
3792 convertToUnqualifiedObjCType(T);
3793 return T != oldT;
3794}
3795
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003796/// convertFunctionTypeOfBlocks - This routine converts a function type
3797/// whose result type may be a block pointer or whose argument type(s)
3798/// might be block pointers to an equivalent function type replacing
3799/// all block pointers to function pointers.
3800QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3801 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3802 // FTP will be null for closures that don't take arguments.
3803 // Generate a funky cast.
3804 SmallVector<QualType, 8> ArgTypes;
3805 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003806 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003807
3808 if (FTP) {
3809 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3810 E = FTP->arg_type_end(); I && (I != E); ++I) {
3811 QualType t = *I;
3812 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003813 if (convertObjCTypeToCStyleType(t))
3814 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003815 ArgTypes.push_back(t);
3816 }
3817 }
3818 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003819 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003820 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3821 else FuncType = QualType(FT, 0);
3822 return FuncType;
3823}
3824
3825Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3826 // Navigate to relevant type information.
3827 const BlockPointerType *CPT = 0;
3828
3829 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3830 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003831 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3832 CPT = MExpr->getType()->getAs<BlockPointerType>();
3833 }
3834 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3835 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3836 }
3837 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3838 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3839 else if (const ConditionalOperator *CEXPR =
3840 dyn_cast<ConditionalOperator>(BlockExp)) {
3841 Expr *LHSExp = CEXPR->getLHS();
3842 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3843 Expr *RHSExp = CEXPR->getRHS();
3844 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3845 Expr *CONDExp = CEXPR->getCond();
3846 ConditionalOperator *CondExpr =
3847 new (Context) ConditionalOperator(CONDExp,
3848 SourceLocation(), cast<Expr>(LHSStmt),
3849 SourceLocation(), cast<Expr>(RHSStmt),
3850 Exp->getType(), VK_RValue, OK_Ordinary);
3851 return CondExpr;
3852 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3853 CPT = IRE->getType()->getAs<BlockPointerType>();
3854 } else if (const PseudoObjectExpr *POE
3855 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3856 CPT = POE->getType()->castAs<BlockPointerType>();
3857 } else {
3858 assert(1 && "RewriteBlockClass: Bad type");
3859 }
3860 assert(CPT && "RewriteBlockClass: Bad type");
3861 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3862 assert(FT && "RewriteBlockClass: Bad type");
3863 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3864 // FTP will be null for closures that don't take arguments.
3865
3866 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3867 SourceLocation(), SourceLocation(),
3868 &Context->Idents.get("__block_impl"));
3869 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3870
3871 // Generate a funky cast.
3872 SmallVector<QualType, 8> ArgTypes;
3873
3874 // Push the block argument type.
3875 ArgTypes.push_back(PtrBlock);
3876 if (FTP) {
3877 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3878 E = FTP->arg_type_end(); I && (I != E); ++I) {
3879 QualType t = *I;
3880 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3881 if (!convertBlockPointerToFunctionPointer(t))
3882 convertToUnqualifiedObjCType(t);
3883 ArgTypes.push_back(t);
3884 }
3885 }
3886 // Now do the pointer to function cast.
3887 QualType PtrToFuncCastType
3888 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3889
3890 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3891
3892 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3893 CK_BitCast,
3894 const_cast<Expr*>(BlockExp));
3895 // Don't forget the parens to enforce the proper binding.
3896 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3897 BlkCast);
3898 //PE->dump();
3899
3900 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3901 SourceLocation(),
3902 &Context->Idents.get("FuncPtr"),
3903 Context->VoidPtrTy, 0,
3904 /*BitWidth=*/0, /*Mutable=*/true,
3905 /*HasInit=*/false);
3906 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3907 FD->getType(), VK_LValue,
3908 OK_Ordinary);
3909
3910
3911 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3912 CK_BitCast, ME);
3913 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3914
3915 SmallVector<Expr*, 8> BlkExprs;
3916 // Add the implicit argument.
3917 BlkExprs.push_back(BlkCast);
3918 // Add the user arguments.
3919 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3920 E = Exp->arg_end(); I != E; ++I) {
3921 BlkExprs.push_back(*I);
3922 }
3923 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3924 BlkExprs.size(),
3925 Exp->getType(), VK_RValue,
3926 SourceLocation());
3927 return CE;
3928}
3929
3930// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003931// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003932// For example:
3933//
3934// int main() {
3935// __block Foo *f;
3936// __block int i;
3937//
3938// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003939// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003940// i = 77;
3941// };
3942//}
John McCallf4b88a42012-03-10 09:33:50 +00003943Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003944 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3945 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003946 ValueDecl *VD = DeclRefExp->getDecl();
3947 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003948
3949 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3950 SourceLocation(),
3951 &Context->Idents.get("__forwarding"),
3952 Context->VoidPtrTy, 0,
3953 /*BitWidth=*/0, /*Mutable=*/true,
3954 /*HasInit=*/false);
3955 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3956 FD, SourceLocation(),
3957 FD->getType(), VK_LValue,
3958 OK_Ordinary);
3959
3960 StringRef Name = VD->getName();
3961 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3962 &Context->Idents.get(Name),
3963 Context->VoidPtrTy, 0,
3964 /*BitWidth=*/0, /*Mutable=*/true,
3965 /*HasInit=*/false);
3966 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3967 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3968
3969
3970
3971 // Need parens to enforce precedence.
3972 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3973 DeclRefExp->getExprLoc(),
3974 ME);
3975 ReplaceStmt(DeclRefExp, PE);
3976 return PE;
3977}
3978
3979// Rewrites the imported local variable V with external storage
3980// (static, extern, etc.) as *V
3981//
3982Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3983 ValueDecl *VD = DRE->getDecl();
3984 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3985 if (!ImportedLocalExternalDecls.count(Var))
3986 return DRE;
3987 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3988 VK_LValue, OK_Ordinary,
3989 DRE->getLocation());
3990 // Need parens to enforce precedence.
3991 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3992 Exp);
3993 ReplaceStmt(DRE, PE);
3994 return PE;
3995}
3996
3997void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3998 SourceLocation LocStart = CE->getLParenLoc();
3999 SourceLocation LocEnd = CE->getRParenLoc();
4000
4001 // Need to avoid trying to rewrite synthesized casts.
4002 if (LocStart.isInvalid())
4003 return;
4004 // Need to avoid trying to rewrite casts contained in macros.
4005 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4006 return;
4007
4008 const char *startBuf = SM->getCharacterData(LocStart);
4009 const char *endBuf = SM->getCharacterData(LocEnd);
4010 QualType QT = CE->getType();
4011 const Type* TypePtr = QT->getAs<Type>();
4012 if (isa<TypeOfExprType>(TypePtr)) {
4013 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4014 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4015 std::string TypeAsString = "(";
4016 RewriteBlockPointerType(TypeAsString, QT);
4017 TypeAsString += ")";
4018 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4019 return;
4020 }
4021 // advance the location to startArgList.
4022 const char *argPtr = startBuf;
4023
4024 while (*argPtr++ && (argPtr < endBuf)) {
4025 switch (*argPtr) {
4026 case '^':
4027 // Replace the '^' with '*'.
4028 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4029 ReplaceText(LocStart, 1, "*");
4030 break;
4031 }
4032 }
4033 return;
4034}
4035
4036void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4037 SourceLocation DeclLoc = FD->getLocation();
4038 unsigned parenCount = 0;
4039
4040 // We have 1 or more arguments that have closure pointers.
4041 const char *startBuf = SM->getCharacterData(DeclLoc);
4042 const char *startArgList = strchr(startBuf, '(');
4043
4044 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4045
4046 parenCount++;
4047 // advance the location to startArgList.
4048 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4049 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4050
4051 const char *argPtr = startArgList;
4052
4053 while (*argPtr++ && parenCount) {
4054 switch (*argPtr) {
4055 case '^':
4056 // Replace the '^' with '*'.
4057 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4058 ReplaceText(DeclLoc, 1, "*");
4059 break;
4060 case '(':
4061 parenCount++;
4062 break;
4063 case ')':
4064 parenCount--;
4065 break;
4066 }
4067 }
4068 return;
4069}
4070
4071bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4072 const FunctionProtoType *FTP;
4073 const PointerType *PT = QT->getAs<PointerType>();
4074 if (PT) {
4075 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4076 } else {
4077 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4078 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4079 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4080 }
4081 if (FTP) {
4082 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4083 E = FTP->arg_type_end(); I != E; ++I)
4084 if (isTopLevelBlockPointerType(*I))
4085 return true;
4086 }
4087 return false;
4088}
4089
4090bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4091 const FunctionProtoType *FTP;
4092 const PointerType *PT = QT->getAs<PointerType>();
4093 if (PT) {
4094 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4095 } else {
4096 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4097 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4098 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4099 }
4100 if (FTP) {
4101 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4102 E = FTP->arg_type_end(); I != E; ++I) {
4103 if ((*I)->isObjCQualifiedIdType())
4104 return true;
4105 if ((*I)->isObjCObjectPointerType() &&
4106 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4107 return true;
4108 }
4109
4110 }
4111 return false;
4112}
4113
4114void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4115 const char *&RParen) {
4116 const char *argPtr = strchr(Name, '(');
4117 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4118
4119 LParen = argPtr; // output the start.
4120 argPtr++; // skip past the left paren.
4121 unsigned parenCount = 1;
4122
4123 while (*argPtr && parenCount) {
4124 switch (*argPtr) {
4125 case '(': parenCount++; break;
4126 case ')': parenCount--; break;
4127 default: break;
4128 }
4129 if (parenCount) argPtr++;
4130 }
4131 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4132 RParen = argPtr; // output the end
4133}
4134
4135void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4136 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4137 RewriteBlockPointerFunctionArgs(FD);
4138 return;
4139 }
4140 // Handle Variables and Typedefs.
4141 SourceLocation DeclLoc = ND->getLocation();
4142 QualType DeclT;
4143 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4144 DeclT = VD->getType();
4145 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4146 DeclT = TDD->getUnderlyingType();
4147 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4148 DeclT = FD->getType();
4149 else
4150 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4151
4152 const char *startBuf = SM->getCharacterData(DeclLoc);
4153 const char *endBuf = startBuf;
4154 // scan backward (from the decl location) for the end of the previous decl.
4155 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4156 startBuf--;
4157 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4158 std::string buf;
4159 unsigned OrigLength=0;
4160 // *startBuf != '^' if we are dealing with a pointer to function that
4161 // may take block argument types (which will be handled below).
4162 if (*startBuf == '^') {
4163 // Replace the '^' with '*', computing a negative offset.
4164 buf = '*';
4165 startBuf++;
4166 OrigLength++;
4167 }
4168 while (*startBuf != ')') {
4169 buf += *startBuf;
4170 startBuf++;
4171 OrigLength++;
4172 }
4173 buf += ')';
4174 OrigLength++;
4175
4176 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4177 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4178 // Replace the '^' with '*' for arguments.
4179 // Replace id<P> with id/*<>*/
4180 DeclLoc = ND->getLocation();
4181 startBuf = SM->getCharacterData(DeclLoc);
4182 const char *argListBegin, *argListEnd;
4183 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4184 while (argListBegin < argListEnd) {
4185 if (*argListBegin == '^')
4186 buf += '*';
4187 else if (*argListBegin == '<') {
4188 buf += "/*";
4189 buf += *argListBegin++;
4190 OrigLength++;;
4191 while (*argListBegin != '>') {
4192 buf += *argListBegin++;
4193 OrigLength++;
4194 }
4195 buf += *argListBegin;
4196 buf += "*/";
4197 }
4198 else
4199 buf += *argListBegin;
4200 argListBegin++;
4201 OrigLength++;
4202 }
4203 buf += ')';
4204 OrigLength++;
4205 }
4206 ReplaceText(Start, OrigLength, buf);
4207
4208 return;
4209}
4210
4211
4212/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4213/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4214/// struct Block_byref_id_object *src) {
4215/// _Block_object_assign (&_dest->object, _src->object,
4216/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4217/// [|BLOCK_FIELD_IS_WEAK]) // object
4218/// _Block_object_assign(&_dest->object, _src->object,
4219/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4220/// [|BLOCK_FIELD_IS_WEAK]) // block
4221/// }
4222/// And:
4223/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4224/// _Block_object_dispose(_src->object,
4225/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4226/// [|BLOCK_FIELD_IS_WEAK]) // object
4227/// _Block_object_dispose(_src->object,
4228/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4229/// [|BLOCK_FIELD_IS_WEAK]) // block
4230/// }
4231
4232std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4233 int flag) {
4234 std::string S;
4235 if (CopyDestroyCache.count(flag))
4236 return S;
4237 CopyDestroyCache.insert(flag);
4238 S = "static void __Block_byref_id_object_copy_";
4239 S += utostr(flag);
4240 S += "(void *dst, void *src) {\n";
4241
4242 // offset into the object pointer is computed as:
4243 // void * + void* + int + int + void* + void *
4244 unsigned IntSize =
4245 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4246 unsigned VoidPtrSize =
4247 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4248
4249 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4250 S += " _Block_object_assign((char*)dst + ";
4251 S += utostr(offset);
4252 S += ", *(void * *) ((char*)src + ";
4253 S += utostr(offset);
4254 S += "), ";
4255 S += utostr(flag);
4256 S += ");\n}\n";
4257
4258 S += "static void __Block_byref_id_object_dispose_";
4259 S += utostr(flag);
4260 S += "(void *src) {\n";
4261 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4262 S += utostr(offset);
4263 S += "), ";
4264 S += utostr(flag);
4265 S += ");\n}\n";
4266 return S;
4267}
4268
4269/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4270/// the declaration into:
4271/// struct __Block_byref_ND {
4272/// void *__isa; // NULL for everything except __weak pointers
4273/// struct __Block_byref_ND *__forwarding;
4274/// int32_t __flags;
4275/// int32_t __size;
4276/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4277/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4278/// typex ND;
4279/// };
4280///
4281/// It then replaces declaration of ND variable with:
4282/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4283/// __size=sizeof(struct __Block_byref_ND),
4284/// ND=initializer-if-any};
4285///
4286///
4287void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4288 // Insert declaration for the function in which block literal is
4289 // used.
4290 if (CurFunctionDeclToDeclareForBlock)
4291 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4292 int flag = 0;
4293 int isa = 0;
4294 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4295 if (DeclLoc.isInvalid())
4296 // If type location is missing, it is because of missing type (a warning).
4297 // Use variable's location which is good for this case.
4298 DeclLoc = ND->getLocation();
4299 const char *startBuf = SM->getCharacterData(DeclLoc);
4300 SourceLocation X = ND->getLocEnd();
4301 X = SM->getExpansionLoc(X);
4302 const char *endBuf = SM->getCharacterData(X);
4303 std::string Name(ND->getNameAsString());
4304 std::string ByrefType;
4305 RewriteByRefString(ByrefType, Name, ND, true);
4306 ByrefType += " {\n";
4307 ByrefType += " void *__isa;\n";
4308 RewriteByRefString(ByrefType, Name, ND);
4309 ByrefType += " *__forwarding;\n";
4310 ByrefType += " int __flags;\n";
4311 ByrefType += " int __size;\n";
4312 // Add void *__Block_byref_id_object_copy;
4313 // void *__Block_byref_id_object_dispose; if needed.
4314 QualType Ty = ND->getType();
4315 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4316 if (HasCopyAndDispose) {
4317 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4318 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4319 }
4320
4321 QualType T = Ty;
4322 (void)convertBlockPointerToFunctionPointer(T);
4323 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4324
4325 ByrefType += " " + Name + ";\n";
4326 ByrefType += "};\n";
4327 // Insert this type in global scope. It is needed by helper function.
4328 SourceLocation FunLocStart;
4329 if (CurFunctionDef)
4330 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4331 else {
4332 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4333 FunLocStart = CurMethodDef->getLocStart();
4334 }
4335 InsertText(FunLocStart, ByrefType);
4336 if (Ty.isObjCGCWeak()) {
4337 flag |= BLOCK_FIELD_IS_WEAK;
4338 isa = 1;
4339 }
4340
4341 if (HasCopyAndDispose) {
4342 flag = BLOCK_BYREF_CALLER;
4343 QualType Ty = ND->getType();
4344 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4345 if (Ty->isBlockPointerType())
4346 flag |= BLOCK_FIELD_IS_BLOCK;
4347 else
4348 flag |= BLOCK_FIELD_IS_OBJECT;
4349 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4350 if (!HF.empty())
4351 InsertText(FunLocStart, HF);
4352 }
4353
4354 // struct __Block_byref_ND ND =
4355 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4356 // initializer-if-any};
4357 bool hasInit = (ND->getInit() != 0);
4358 unsigned flags = 0;
4359 if (HasCopyAndDispose)
4360 flags |= BLOCK_HAS_COPY_DISPOSE;
4361 Name = ND->getNameAsString();
4362 ByrefType.clear();
4363 RewriteByRefString(ByrefType, Name, ND);
4364 std::string ForwardingCastType("(");
4365 ForwardingCastType += ByrefType + " *)";
4366 if (!hasInit) {
4367 ByrefType += " " + Name + " = {(void*)";
4368 ByrefType += utostr(isa);
4369 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4370 ByrefType += utostr(flags);
4371 ByrefType += ", ";
4372 ByrefType += "sizeof(";
4373 RewriteByRefString(ByrefType, Name, ND);
4374 ByrefType += ")";
4375 if (HasCopyAndDispose) {
4376 ByrefType += ", __Block_byref_id_object_copy_";
4377 ByrefType += utostr(flag);
4378 ByrefType += ", __Block_byref_id_object_dispose_";
4379 ByrefType += utostr(flag);
4380 }
4381 ByrefType += "};\n";
4382 unsigned nameSize = Name.size();
4383 // for block or function pointer declaration. Name is aleady
4384 // part of the declaration.
4385 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4386 nameSize = 1;
4387 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4388 }
4389 else {
4390 SourceLocation startLoc;
4391 Expr *E = ND->getInit();
4392 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4393 startLoc = ECE->getLParenLoc();
4394 else
4395 startLoc = E->getLocStart();
4396 startLoc = SM->getExpansionLoc(startLoc);
4397 endBuf = SM->getCharacterData(startLoc);
4398 ByrefType += " " + Name;
4399 ByrefType += " = {(void*)";
4400 ByrefType += utostr(isa);
4401 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4402 ByrefType += utostr(flags);
4403 ByrefType += ", ";
4404 ByrefType += "sizeof(";
4405 RewriteByRefString(ByrefType, Name, ND);
4406 ByrefType += "), ";
4407 if (HasCopyAndDispose) {
4408 ByrefType += "__Block_byref_id_object_copy_";
4409 ByrefType += utostr(flag);
4410 ByrefType += ", __Block_byref_id_object_dispose_";
4411 ByrefType += utostr(flag);
4412 ByrefType += ", ";
4413 }
4414 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4415
4416 // Complete the newly synthesized compound expression by inserting a right
4417 // curly brace before the end of the declaration.
4418 // FIXME: This approach avoids rewriting the initializer expression. It
4419 // also assumes there is only one declarator. For example, the following
4420 // isn't currently supported by this routine (in general):
4421 //
4422 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4423 //
4424 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4425 const char *semiBuf = strchr(startInitializerBuf, ';');
4426 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4427 SourceLocation semiLoc =
4428 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4429
4430 InsertText(semiLoc, "}");
4431 }
4432 return;
4433}
4434
4435void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4436 // Add initializers for any closure decl refs.
4437 GetBlockDeclRefExprs(Exp->getBody());
4438 if (BlockDeclRefs.size()) {
4439 // Unique all "by copy" declarations.
4440 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004441 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004442 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4443 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4444 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4445 }
4446 }
4447 // Unique all "by ref" declarations.
4448 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004449 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004450 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4451 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4452 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4453 }
4454 }
4455 // Find any imported blocks...they will need special attention.
4456 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004457 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004458 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4459 BlockDeclRefs[i]->getType()->isBlockPointerType())
4460 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4461 }
4462}
4463
4464FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4465 IdentifierInfo *ID = &Context->Idents.get(name);
4466 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4467 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4468 SourceLocation(), ID, FType, 0, SC_Extern,
4469 SC_None, false, false);
4470}
4471
4472Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004473 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004474 const BlockDecl *block = Exp->getBlockDecl();
4475 Blocks.push_back(Exp);
4476
4477 CollectBlockDeclRefInfo(Exp);
4478
4479 // Add inner imported variables now used in current block.
4480 int countOfInnerDecls = 0;
4481 if (!InnerBlockDeclRefs.empty()) {
4482 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004483 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004484 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004485 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004486 // We need to save the copied-in variables in nested
4487 // blocks because it is needed at the end for some of the API generations.
4488 // See SynthesizeBlockLiterals routine.
4489 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4490 BlockDeclRefs.push_back(Exp);
4491 BlockByCopyDeclsPtrSet.insert(VD);
4492 BlockByCopyDecls.push_back(VD);
4493 }
John McCallf4b88a42012-03-10 09:33:50 +00004494 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004495 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4496 BlockDeclRefs.push_back(Exp);
4497 BlockByRefDeclsPtrSet.insert(VD);
4498 BlockByRefDecls.push_back(VD);
4499 }
4500 }
4501 // Find any imported blocks...they will need special attention.
4502 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004503 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004504 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4505 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4506 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4507 }
4508 InnerDeclRefsCount.push_back(countOfInnerDecls);
4509
4510 std::string FuncName;
4511
4512 if (CurFunctionDef)
4513 FuncName = CurFunctionDef->getNameAsString();
4514 else if (CurMethodDef)
4515 BuildUniqueMethodName(FuncName, CurMethodDef);
4516 else if (GlobalVarDecl)
4517 FuncName = std::string(GlobalVarDecl->getNameAsString());
4518
4519 std::string BlockNumber = utostr(Blocks.size()-1);
4520
4521 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4522 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4523
4524 // Get a pointer to the function type so we can cast appropriately.
4525 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4526 QualType FType = Context->getPointerType(BFT);
4527
4528 FunctionDecl *FD;
4529 Expr *NewRep;
4530
4531 // Simulate a contructor call...
4532 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004533 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004534 SourceLocation());
4535
4536 SmallVector<Expr*, 4> InitExprs;
4537
4538 // Initialize the block function.
4539 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004540 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4541 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004542 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4543 CK_BitCast, Arg);
4544 InitExprs.push_back(castExpr);
4545
4546 // Initialize the block descriptor.
4547 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4548
4549 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4550 SourceLocation(), SourceLocation(),
4551 &Context->Idents.get(DescData.c_str()),
4552 Context->VoidPtrTy, 0,
4553 SC_Static, SC_None);
4554 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004555 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004556 Context->VoidPtrTy,
4557 VK_LValue,
4558 SourceLocation()),
4559 UO_AddrOf,
4560 Context->getPointerType(Context->VoidPtrTy),
4561 VK_RValue, OK_Ordinary,
4562 SourceLocation());
4563 InitExprs.push_back(DescRefExpr);
4564
4565 // Add initializers for any closure decl refs.
4566 if (BlockDeclRefs.size()) {
4567 Expr *Exp;
4568 // Output all "by copy" declarations.
4569 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4570 E = BlockByCopyDecls.end(); I != E; ++I) {
4571 if (isObjCType((*I)->getType())) {
4572 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4573 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004574 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4575 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004576 if (HasLocalVariableExternalStorage(*I)) {
4577 QualType QT = (*I)->getType();
4578 QT = Context->getPointerType(QT);
4579 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4580 OK_Ordinary, SourceLocation());
4581 }
4582 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4583 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004584 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4585 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004586 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4587 CK_BitCast, Arg);
4588 } else {
4589 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004590 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4591 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004592 if (HasLocalVariableExternalStorage(*I)) {
4593 QualType QT = (*I)->getType();
4594 QT = Context->getPointerType(QT);
4595 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4596 OK_Ordinary, SourceLocation());
4597 }
4598
4599 }
4600 InitExprs.push_back(Exp);
4601 }
4602 // Output all "by ref" declarations.
4603 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4604 E = BlockByRefDecls.end(); I != E; ++I) {
4605 ValueDecl *ND = (*I);
4606 std::string Name(ND->getNameAsString());
4607 std::string RecName;
4608 RewriteByRefString(RecName, Name, ND, true);
4609 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4610 + sizeof("struct"));
4611 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4612 SourceLocation(), SourceLocation(),
4613 II);
4614 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4615 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4616
4617 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004618 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004619 SourceLocation());
4620 bool isNestedCapturedVar = false;
4621 if (block)
4622 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4623 ce = block->capture_end(); ci != ce; ++ci) {
4624 const VarDecl *variable = ci->getVariable();
4625 if (variable == ND && ci->isNested()) {
4626 assert (ci->isByRef() &&
4627 "SynthBlockInitExpr - captured block variable is not byref");
4628 isNestedCapturedVar = true;
4629 break;
4630 }
4631 }
4632 // captured nested byref variable has its address passed. Do not take
4633 // its address again.
4634 if (!isNestedCapturedVar)
4635 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4636 Context->getPointerType(Exp->getType()),
4637 VK_RValue, OK_Ordinary, SourceLocation());
4638 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4639 InitExprs.push_back(Exp);
4640 }
4641 }
4642 if (ImportedBlockDecls.size()) {
4643 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4644 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4645 unsigned IntSize =
4646 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4647 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4648 Context->IntTy, SourceLocation());
4649 InitExprs.push_back(FlagExp);
4650 }
4651 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4652 FType, VK_LValue, SourceLocation());
4653 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4654 Context->getPointerType(NewRep->getType()),
4655 VK_RValue, OK_Ordinary, SourceLocation());
4656 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4657 NewRep);
4658 BlockDeclRefs.clear();
4659 BlockByRefDecls.clear();
4660 BlockByRefDeclsPtrSet.clear();
4661 BlockByCopyDecls.clear();
4662 BlockByCopyDeclsPtrSet.clear();
4663 ImportedBlockDecls.clear();
4664 return NewRep;
4665}
4666
4667bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4668 if (const ObjCForCollectionStmt * CS =
4669 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4670 return CS->getElement() == DS;
4671 return false;
4672}
4673
4674//===----------------------------------------------------------------------===//
4675// Function Body / Expression rewriting
4676//===----------------------------------------------------------------------===//
4677
4678Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4679 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4680 isa<DoStmt>(S) || isa<ForStmt>(S))
4681 Stmts.push_back(S);
4682 else if (isa<ObjCForCollectionStmt>(S)) {
4683 Stmts.push_back(S);
4684 ObjCBcLabelNo.push_back(++BcLabelCount);
4685 }
4686
4687 // Pseudo-object operations and ivar references need special
4688 // treatment because we're going to recursively rewrite them.
4689 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4690 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4691 return RewritePropertyOrImplicitSetter(PseudoOp);
4692 } else {
4693 return RewritePropertyOrImplicitGetter(PseudoOp);
4694 }
4695 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4696 return RewriteObjCIvarRefExpr(IvarRefExpr);
4697 }
4698
4699 SourceRange OrigStmtRange = S->getSourceRange();
4700
4701 // Perform a bottom up rewrite of all children.
4702 for (Stmt::child_range CI = S->children(); CI; ++CI)
4703 if (*CI) {
4704 Stmt *childStmt = (*CI);
4705 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4706 if (newStmt) {
4707 *CI = newStmt;
4708 }
4709 }
4710
4711 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004712 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004713 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4714 InnerContexts.insert(BE->getBlockDecl());
4715 ImportedLocalExternalDecls.clear();
4716 GetInnerBlockDeclRefExprs(BE->getBody(),
4717 InnerBlockDeclRefs, InnerContexts);
4718 // Rewrite the block body in place.
4719 Stmt *SaveCurrentBody = CurrentBody;
4720 CurrentBody = BE->getBody();
4721 PropParentMap = 0;
4722 // block literal on rhs of a property-dot-sytax assignment
4723 // must be replaced by its synthesize ast so getRewrittenText
4724 // works as expected. In this case, what actually ends up on RHS
4725 // is the blockTranscribed which is the helper function for the
4726 // block literal; as in: self.c = ^() {[ace ARR];};
4727 bool saveDisableReplaceStmt = DisableReplaceStmt;
4728 DisableReplaceStmt = false;
4729 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4730 DisableReplaceStmt = saveDisableReplaceStmt;
4731 CurrentBody = SaveCurrentBody;
4732 PropParentMap = 0;
4733 ImportedLocalExternalDecls.clear();
4734 // Now we snarf the rewritten text and stash it away for later use.
4735 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4736 RewrittenBlockExprs[BE] = Str;
4737
4738 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4739
4740 //blockTranscribed->dump();
4741 ReplaceStmt(S, blockTranscribed);
4742 return blockTranscribed;
4743 }
4744 // Handle specific things.
4745 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4746 return RewriteAtEncode(AtEncode);
4747
4748 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4749 return RewriteAtSelector(AtSelector);
4750
4751 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4752 return RewriteObjCStringLiteral(AtString);
4753
4754 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4755#if 0
4756 // Before we rewrite it, put the original message expression in a comment.
4757 SourceLocation startLoc = MessExpr->getLocStart();
4758 SourceLocation endLoc = MessExpr->getLocEnd();
4759
4760 const char *startBuf = SM->getCharacterData(startLoc);
4761 const char *endBuf = SM->getCharacterData(endLoc);
4762
4763 std::string messString;
4764 messString += "// ";
4765 messString.append(startBuf, endBuf-startBuf+1);
4766 messString += "\n";
4767
4768 // FIXME: Missing definition of
4769 // InsertText(clang::SourceLocation, char const*, unsigned int).
4770 // InsertText(startLoc, messString.c_str(), messString.size());
4771 // Tried this, but it didn't work either...
4772 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4773#endif
4774 return RewriteMessageExpr(MessExpr);
4775 }
4776
4777 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4778 return RewriteObjCTryStmt(StmtTry);
4779
4780 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4781 return RewriteObjCSynchronizedStmt(StmtTry);
4782
4783 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4784 return RewriteObjCThrowStmt(StmtThrow);
4785
4786 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4787 return RewriteObjCProtocolExpr(ProtocolExp);
4788
4789 if (ObjCForCollectionStmt *StmtForCollection =
4790 dyn_cast<ObjCForCollectionStmt>(S))
4791 return RewriteObjCForCollectionStmt(StmtForCollection,
4792 OrigStmtRange.getEnd());
4793 if (BreakStmt *StmtBreakStmt =
4794 dyn_cast<BreakStmt>(S))
4795 return RewriteBreakStmt(StmtBreakStmt);
4796 if (ContinueStmt *StmtContinueStmt =
4797 dyn_cast<ContinueStmt>(S))
4798 return RewriteContinueStmt(StmtContinueStmt);
4799
4800 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4801 // and cast exprs.
4802 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4803 // FIXME: What we're doing here is modifying the type-specifier that
4804 // precedes the first Decl. In the future the DeclGroup should have
4805 // a separate type-specifier that we can rewrite.
4806 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4807 // the context of an ObjCForCollectionStmt. For example:
4808 // NSArray *someArray;
4809 // for (id <FooProtocol> index in someArray) ;
4810 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4811 // and it depends on the original text locations/positions.
4812 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4813 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4814
4815 // Blocks rewrite rules.
4816 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4817 DI != DE; ++DI) {
4818 Decl *SD = *DI;
4819 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4820 if (isTopLevelBlockPointerType(ND->getType()))
4821 RewriteBlockPointerDecl(ND);
4822 else if (ND->getType()->isFunctionPointerType())
4823 CheckFunctionPointerDecl(ND->getType(), ND);
4824 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4825 if (VD->hasAttr<BlocksAttr>()) {
4826 static unsigned uniqueByrefDeclCount = 0;
4827 assert(!BlockByRefDeclNo.count(ND) &&
4828 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4829 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4830 RewriteByRefVar(VD);
4831 }
4832 else
4833 RewriteTypeOfDecl(VD);
4834 }
4835 }
4836 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4837 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4838 RewriteBlockPointerDecl(TD);
4839 else if (TD->getUnderlyingType()->isFunctionPointerType())
4840 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4841 }
4842 }
4843 }
4844
4845 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4846 RewriteObjCQualifiedInterfaceTypes(CE);
4847
4848 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4849 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4850 assert(!Stmts.empty() && "Statement stack is empty");
4851 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4852 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4853 && "Statement stack mismatch");
4854 Stmts.pop_back();
4855 }
4856 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004857 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4858 ValueDecl *VD = DRE->getDecl();
4859 if (VD->hasAttr<BlocksAttr>())
4860 return RewriteBlockDeclRefExpr(DRE);
4861 if (HasLocalVariableExternalStorage(VD))
4862 return RewriteLocalVariableExternalStorage(DRE);
4863 }
4864
4865 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4866 if (CE->getCallee()->getType()->isBlockPointerType()) {
4867 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4868 ReplaceStmt(S, BlockCall);
4869 return BlockCall;
4870 }
4871 }
4872 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4873 RewriteCastExpr(CE);
4874 }
4875#if 0
4876 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4877 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4878 ICE->getSubExpr(),
4879 SourceLocation());
4880 // Get the new text.
4881 std::string SStr;
4882 llvm::raw_string_ostream Buf(SStr);
4883 Replacement->printPretty(Buf, *Context);
4884 const std::string &Str = Buf.str();
4885
4886 printf("CAST = %s\n", &Str[0]);
4887 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4888 delete S;
4889 return Replacement;
4890 }
4891#endif
4892 // Return this stmt unmodified.
4893 return S;
4894}
4895
4896void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4897 for (RecordDecl::field_iterator i = RD->field_begin(),
4898 e = RD->field_end(); i != e; ++i) {
4899 FieldDecl *FD = *i;
4900 if (isTopLevelBlockPointerType(FD->getType()))
4901 RewriteBlockPointerDecl(FD);
4902 if (FD->getType()->isObjCQualifiedIdType() ||
4903 FD->getType()->isObjCQualifiedInterfaceType())
4904 RewriteObjCQualifiedInterfaceTypes(FD);
4905 }
4906}
4907
4908/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4909/// main file of the input.
4910void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4911 switch (D->getKind()) {
4912 case Decl::Function: {
4913 FunctionDecl *FD = cast<FunctionDecl>(D);
4914 if (FD->isOverloadedOperator())
4915 return;
4916
4917 // Since function prototypes don't have ParmDecl's, we check the function
4918 // prototype. This enables us to rewrite function declarations and
4919 // definitions using the same code.
4920 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4921
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004922 if (!FD->isThisDeclarationADefinition())
4923 break;
4924
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004925 // FIXME: If this should support Obj-C++, support CXXTryStmt
4926 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4927 CurFunctionDef = FD;
4928 CurFunctionDeclToDeclareForBlock = FD;
4929 CurrentBody = Body;
4930 Body =
4931 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4932 FD->setBody(Body);
4933 CurrentBody = 0;
4934 if (PropParentMap) {
4935 delete PropParentMap;
4936 PropParentMap = 0;
4937 }
4938 // This synthesizes and inserts the block "impl" struct, invoke function,
4939 // and any copy/dispose helper functions.
4940 InsertBlockLiteralsWithinFunction(FD);
4941 CurFunctionDef = 0;
4942 CurFunctionDeclToDeclareForBlock = 0;
4943 }
4944 break;
4945 }
4946 case Decl::ObjCMethod: {
4947 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4948 if (CompoundStmt *Body = MD->getCompoundBody()) {
4949 CurMethodDef = MD;
4950 CurrentBody = Body;
4951 Body =
4952 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4953 MD->setBody(Body);
4954 CurrentBody = 0;
4955 if (PropParentMap) {
4956 delete PropParentMap;
4957 PropParentMap = 0;
4958 }
4959 InsertBlockLiteralsWithinMethod(MD);
4960 CurMethodDef = 0;
4961 }
4962 break;
4963 }
4964 case Decl::ObjCImplementation: {
4965 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4966 ClassImplementation.push_back(CI);
4967 break;
4968 }
4969 case Decl::ObjCCategoryImpl: {
4970 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4971 CategoryImplementation.push_back(CI);
4972 break;
4973 }
4974 case Decl::Var: {
4975 VarDecl *VD = cast<VarDecl>(D);
4976 RewriteObjCQualifiedInterfaceTypes(VD);
4977 if (isTopLevelBlockPointerType(VD->getType()))
4978 RewriteBlockPointerDecl(VD);
4979 else if (VD->getType()->isFunctionPointerType()) {
4980 CheckFunctionPointerDecl(VD->getType(), VD);
4981 if (VD->getInit()) {
4982 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4983 RewriteCastExpr(CE);
4984 }
4985 }
4986 } else if (VD->getType()->isRecordType()) {
4987 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4988 if (RD->isCompleteDefinition())
4989 RewriteRecordBody(RD);
4990 }
4991 if (VD->getInit()) {
4992 GlobalVarDecl = VD;
4993 CurrentBody = VD->getInit();
4994 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4995 CurrentBody = 0;
4996 if (PropParentMap) {
4997 delete PropParentMap;
4998 PropParentMap = 0;
4999 }
5000 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5001 GlobalVarDecl = 0;
5002
5003 // This is needed for blocks.
5004 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5005 RewriteCastExpr(CE);
5006 }
5007 }
5008 break;
5009 }
5010 case Decl::TypeAlias:
5011 case Decl::Typedef: {
5012 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5013 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5014 RewriteBlockPointerDecl(TD);
5015 else if (TD->getUnderlyingType()->isFunctionPointerType())
5016 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5017 }
5018 break;
5019 }
5020 case Decl::CXXRecord:
5021 case Decl::Record: {
5022 RecordDecl *RD = cast<RecordDecl>(D);
5023 if (RD->isCompleteDefinition())
5024 RewriteRecordBody(RD);
5025 break;
5026 }
5027 default:
5028 break;
5029 }
5030 // Nothing yet.
5031}
5032
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005033/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5034/// protocol reference symbols in the for of:
5035/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5036static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5037 ObjCProtocolDecl *PDecl,
5038 std::string &Result) {
5039 // Also output .objc_protorefs$B section and its meta-data.
5040 if (Context->getLangOpts().MicrosoftExt)
5041 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5042 Result += "struct _protocol_t *";
5043 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5044 Result += PDecl->getNameAsString();
5045 Result += " = &";
5046 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5047 Result += ";\n";
5048}
5049
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005050void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5051 if (Diags.hasErrorOccurred())
5052 return;
5053
5054 RewriteInclude();
5055
5056 // Here's a great place to add any extra declarations that may be needed.
5057 // Write out meta data for each @protocol(<expr>).
5058 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005059 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005060 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005061 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5062 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005063
5064 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005065 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5066 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5067 // Write struct declaration for the class matching its ivar declarations.
5068 // Note that for modern abi, this is postponed until the end of TU
5069 // because class extensions and the implementation might declare their own
5070 // private ivars.
5071 RewriteInterfaceDecl(CDecl);
5072 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005073
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005074 if (ClassImplementation.size() || CategoryImplementation.size())
5075 RewriteImplementations();
5076
5077 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5078 // we are done.
5079 if (const RewriteBuffer *RewriteBuf =
5080 Rewrite.getRewriteBufferFor(MainFileID)) {
5081 //printf("Changed:\n");
5082 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5083 } else {
5084 llvm::errs() << "No changes\n";
5085 }
5086
5087 if (ClassImplementation.size() || CategoryImplementation.size() ||
5088 ProtocolExprDecls.size()) {
5089 // Rewrite Objective-c meta data*
5090 std::string ResultStr;
5091 RewriteMetaDataIntoBuffer(ResultStr);
5092 // Emit metadata.
5093 *OutFile << ResultStr;
5094 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005095 // Emit ImageInfo;
5096 {
5097 std::string ResultStr;
5098 WriteImageInfo(ResultStr);
5099 *OutFile << ResultStr;
5100 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005101 OutFile->flush();
5102}
5103
5104void RewriteModernObjC::Initialize(ASTContext &context) {
5105 InitializeCommon(context);
5106
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005107 Preamble += "#ifndef __OBJC2__\n";
5108 Preamble += "#define __OBJC2__\n";
5109 Preamble += "#endif\n";
5110
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005111 // declaring objc_selector outside the parameter list removes a silly
5112 // scope related warning...
5113 if (IsHeader)
5114 Preamble = "#pragma once\n";
5115 Preamble += "struct objc_selector; struct objc_class;\n";
5116 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5117 Preamble += "struct objc_object *superClass; ";
5118 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005119 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005120 // These are currently generated.
5121 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005122 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005123 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5124 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005125 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5126 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005127 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005128 // These are generated but not necessary for functionality.
5129 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5130 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005131 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5132 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005133 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005134
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005135 // These need be generated for performance. Currently they are not,
5136 // using API calls instead.
5137 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5138 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5139 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5140
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005141 // Add a constructor for creating temporary objects.
5142 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5143 ": ";
5144 Preamble += "object(o), superClass(s) {} ";
5145 }
5146 Preamble += "};\n";
5147 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5148 Preamble += "typedef struct objc_object Protocol;\n";
5149 Preamble += "#define _REWRITER_typedef_Protocol\n";
5150 Preamble += "#endif\n";
5151 if (LangOpts.MicrosoftExt) {
5152 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5153 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5154 } else
5155 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5156 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5157 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5158 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5159 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5160 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5161 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5162 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5163 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5164 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5165 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5166 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5167 Preamble += "(const char *);\n";
5168 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5169 Preamble += "(struct objc_class *);\n";
5170 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5171 Preamble += "(const char *);\n";
Fariborz Jahanianb1228182012-03-15 22:42:15 +00005172 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(id);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005173 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5174 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5175 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5176 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5177 Preamble += "(struct objc_class *, struct objc_object *);\n";
5178 // @synchronized hooks.
Fariborz Jahanian542125f2012-03-16 21:33:16 +00005179 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(id);\n";
5180 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(id);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005181 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5182 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5183 Preamble += "struct __objcFastEnumerationState {\n\t";
5184 Preamble += "unsigned long state;\n\t";
5185 Preamble += "void **itemsPtr;\n\t";
5186 Preamble += "unsigned long *mutationsPtr;\n\t";
5187 Preamble += "unsigned long extra[5];\n};\n";
5188 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5189 Preamble += "#define __FASTENUMERATIONSTATE\n";
5190 Preamble += "#endif\n";
5191 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5192 Preamble += "struct __NSConstantStringImpl {\n";
5193 Preamble += " int *isa;\n";
5194 Preamble += " int flags;\n";
5195 Preamble += " char *str;\n";
5196 Preamble += " long length;\n";
5197 Preamble += "};\n";
5198 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5199 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5200 Preamble += "#else\n";
5201 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5202 Preamble += "#endif\n";
5203 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5204 Preamble += "#endif\n";
5205 // Blocks preamble.
5206 Preamble += "#ifndef BLOCK_IMPL\n";
5207 Preamble += "#define BLOCK_IMPL\n";
5208 Preamble += "struct __block_impl {\n";
5209 Preamble += " void *isa;\n";
5210 Preamble += " int Flags;\n";
5211 Preamble += " int Reserved;\n";
5212 Preamble += " void *FuncPtr;\n";
5213 Preamble += "};\n";
5214 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5215 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5216 Preamble += "extern \"C\" __declspec(dllexport) "
5217 "void _Block_object_assign(void *, const void *, const int);\n";
5218 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5219 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5220 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5221 Preamble += "#else\n";
5222 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5223 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5224 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5225 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5226 Preamble += "#endif\n";
5227 Preamble += "#endif\n";
5228 if (LangOpts.MicrosoftExt) {
5229 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5230 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5231 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5232 Preamble += "#define __attribute__(X)\n";
5233 Preamble += "#endif\n";
5234 Preamble += "#define __weak\n";
5235 }
5236 else {
5237 Preamble += "#define __block\n";
5238 Preamble += "#define __weak\n";
5239 }
5240 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5241 // as this avoids warning in any 64bit/32bit compilation model.
5242 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5243}
5244
5245/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5246/// ivar offset.
5247void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5248 std::string &Result) {
5249 if (ivar->isBitField()) {
5250 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5251 // place all bitfields at offset 0.
5252 Result += "0";
5253 } else {
5254 Result += "__OFFSETOFIVAR__(struct ";
5255 Result += ivar->getContainingInterface()->getNameAsString();
5256 if (LangOpts.MicrosoftExt)
5257 Result += "_IMPL";
5258 Result += ", ";
5259 Result += ivar->getNameAsString();
5260 Result += ")";
5261 }
5262}
5263
5264/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5265/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005266/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005267/// char *attributes;
5268/// }
5269
5270/// struct _prop_list_t {
5271/// uint32_t entsize; // sizeof(struct _prop_t)
5272/// uint32_t count_of_properties;
5273/// struct _prop_t prop_list[count_of_properties];
5274/// }
5275
5276/// struct _protocol_t;
5277
5278/// struct _protocol_list_t {
5279/// long protocol_count; // Note, this is 32/64 bit
5280/// struct _protocol_t * protocol_list[protocol_count];
5281/// }
5282
5283/// struct _objc_method {
5284/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005285/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005286/// char *_imp;
5287/// }
5288
5289/// struct _method_list_t {
5290/// uint32_t entsize; // sizeof(struct _objc_method)
5291/// uint32_t method_count;
5292/// struct _objc_method method_list[method_count];
5293/// }
5294
5295/// struct _protocol_t {
5296/// id isa; // NULL
5297/// const char * const protocol_name;
5298/// const struct _protocol_list_t * protocol_list; // super protocols
5299/// const struct method_list_t * const instance_methods;
5300/// const struct method_list_t * const class_methods;
5301/// const struct method_list_t *optionalInstanceMethods;
5302/// const struct method_list_t *optionalClassMethods;
5303/// const struct _prop_list_t * properties;
5304/// const uint32_t size; // sizeof(struct _protocol_t)
5305/// const uint32_t flags; // = 0
5306/// const char ** extendedMethodTypes;
5307/// }
5308
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005309/// struct _ivar_t {
5310/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005311/// const char *name;
5312/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005313/// uint32_t alignment;
5314/// uint32_t size;
5315/// }
5316
5317/// struct _ivar_list_t {
5318/// uint32 entsize; // sizeof(struct _ivar_t)
5319/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005320/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005321/// }
5322
5323/// struct _class_ro_t {
5324/// uint32_t const flags;
5325/// uint32_t const instanceStart;
5326/// uint32_t const instanceSize;
5327/// uint32_t const reserved; // only when building for 64bit targets
5328/// const uint8_t * const ivarLayout;
5329/// const char *const name;
5330/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005331/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005332/// const struct _ivar_list_t *const ivars;
5333/// const uint8_t * const weakIvarLayout;
5334/// const struct _prop_list_t * const properties;
5335/// }
5336
5337/// struct _class_t {
5338/// struct _class_t *isa;
5339/// struct _class_t * const superclass;
5340/// void *cache;
5341/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005342/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005343/// }
5344
5345/// struct _category_t {
5346/// const char * const name;
5347/// struct _class_t *const cls;
5348/// const struct _method_list_t * const instance_methods;
5349/// const struct _method_list_t * const class_methods;
5350/// const struct _protocol_list_t * const protocols;
5351/// const struct _prop_list_t * const properties;
5352/// }
5353
5354/// MessageRefTy - LLVM for:
5355/// struct _message_ref_t {
5356/// IMP messenger;
5357/// SEL name;
5358/// };
5359
5360/// SuperMessageRefTy - LLVM for:
5361/// struct _super_message_ref_t {
5362/// SUPER_IMP messenger;
5363/// SEL name;
5364/// };
5365
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005366static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005367 static bool meta_data_declared = false;
5368 if (meta_data_declared)
5369 return;
5370
5371 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005372 Result += "\tconst char *name;\n";
5373 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005374 Result += "};\n";
5375
5376 Result += "\nstruct _protocol_t;\n";
5377
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005378 Result += "\nstruct _objc_method {\n";
5379 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005380 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005381 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005382 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005383
5384 Result += "\nstruct _protocol_t {\n";
5385 Result += "\tvoid * isa; // NULL\n";
5386 Result += "\tconst char * const protocol_name;\n";
5387 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5388 Result += "\tconst struct method_list_t * const instance_methods;\n";
5389 Result += "\tconst struct method_list_t * const class_methods;\n";
5390 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5391 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5392 Result += "\tconst struct _prop_list_t * properties;\n";
5393 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5394 Result += "\tconst unsigned int flags; // = 0\n";
5395 Result += "\tconst char ** extendedMethodTypes;\n";
5396 Result += "};\n";
5397
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005398 Result += "\nstruct _ivar_t {\n";
5399 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005400 Result += "\tconst char *name;\n";
5401 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005402 Result += "\tunsigned int alignment;\n";
5403 Result += "\tunsigned int size;\n";
5404 Result += "};\n";
5405
5406 Result += "\nstruct _class_ro_t {\n";
5407 Result += "\tunsigned int const flags;\n";
5408 Result += "\tunsigned int instanceStart;\n";
5409 Result += "\tunsigned int const instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005410 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5411 if (Triple.getArch() == llvm::Triple::x86_64)
5412 Result += "\tunsigned int const reserved;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005413 Result += "\tconst unsigned char * const ivarLayout;\n";
5414 Result += "\tconst char *const name;\n";
5415 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5416 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5417 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5418 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5419 Result += "\tconst struct _prop_list_t *const properties;\n";
5420 Result += "};\n";
5421
5422 Result += "\nstruct _class_t {\n";
5423 Result += "\tstruct _class_t *isa;\n";
5424 Result += "\tstruct _class_t *const superclass;\n";
5425 Result += "\tvoid *cache;\n";
5426 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005427 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005428 Result += "};\n";
5429
5430 Result += "\nstruct _category_t {\n";
5431 Result += "\tconst char * const name;\n";
5432 Result += "\tstruct _class_t *const cls;\n";
5433 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5434 Result += "\tconst struct _method_list_t *const class_methods;\n";
5435 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5436 Result += "\tconst struct _prop_list_t *const properties;\n";
5437 Result += "};\n";
5438
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005439 Result += "extern void *_objc_empty_cache;\n";
5440 Result += "extern void *_objc_empty_vtable;\n";
5441
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005442 meta_data_declared = true;
5443}
5444
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005445static void Write_protocol_list_t_TypeDecl(std::string &Result,
5446 long super_protocol_count) {
5447 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5448 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5449 Result += "\tstruct _protocol_t *super_protocols[";
5450 Result += utostr(super_protocol_count); Result += "];\n";
5451 Result += "}";
5452}
5453
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005454static void Write_method_list_t_TypeDecl(std::string &Result,
5455 unsigned int method_count) {
5456 Result += "struct /*_method_list_t*/"; Result += " {\n";
5457 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5458 Result += "\tunsigned int method_count;\n";
5459 Result += "\tstruct _objc_method method_list[";
5460 Result += utostr(method_count); Result += "];\n";
5461 Result += "}";
5462}
5463
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005464static void Write__prop_list_t_TypeDecl(std::string &Result,
5465 unsigned int property_count) {
5466 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5467 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5468 Result += "\tunsigned int count_of_properties;\n";
5469 Result += "\tstruct _prop_t prop_list[";
5470 Result += utostr(property_count); Result += "];\n";
5471 Result += "}";
5472}
5473
Fariborz Jahanianae932952012-02-10 20:47:10 +00005474static void Write__ivar_list_t_TypeDecl(std::string &Result,
5475 unsigned int ivar_count) {
5476 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5477 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5478 Result += "\tunsigned int count;\n";
5479 Result += "\tstruct _ivar_t ivar_list[";
5480 Result += utostr(ivar_count); Result += "];\n";
5481 Result += "}";
5482}
5483
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005484static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5485 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5486 StringRef VarName,
5487 StringRef ProtocolName) {
5488 if (SuperProtocols.size() > 0) {
5489 Result += "\nstatic ";
5490 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5491 Result += " "; Result += VarName;
5492 Result += ProtocolName;
5493 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5494 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5495 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5496 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5497 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5498 Result += SuperPD->getNameAsString();
5499 if (i == e-1)
5500 Result += "\n};\n";
5501 else
5502 Result += ",\n";
5503 }
5504 }
5505}
5506
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005507static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5508 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005509 ArrayRef<ObjCMethodDecl *> Methods,
5510 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005511 StringRef TopLevelDeclName,
5512 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005513 if (Methods.size() > 0) {
5514 Result += "\nstatic ";
5515 Write_method_list_t_TypeDecl(Result, Methods.size());
5516 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005517 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005518 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5519 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5520 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5521 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5522 ObjCMethodDecl *MD = Methods[i];
5523 if (i == 0)
5524 Result += "\t{{(struct objc_selector *)\"";
5525 else
5526 Result += "\t{(struct objc_selector *)\"";
5527 Result += (MD)->getSelector().getAsString(); Result += "\"";
5528 Result += ", ";
5529 std::string MethodTypeString;
5530 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5531 Result += "\""; Result += MethodTypeString; Result += "\"";
5532 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005533 if (!MethodImpl)
5534 Result += "0";
5535 else {
5536 Result += "(void *)";
5537 Result += RewriteObj.MethodInternalNames[MD];
5538 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005539 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005540 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005541 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005542 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005543 }
5544 Result += "};\n";
5545 }
5546}
5547
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005548static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005549 ASTContext *Context, std::string &Result,
5550 ArrayRef<ObjCPropertyDecl *> Properties,
5551 const Decl *Container,
5552 StringRef VarName,
5553 StringRef ProtocolName) {
5554 if (Properties.size() > 0) {
5555 Result += "\nstatic ";
5556 Write__prop_list_t_TypeDecl(Result, Properties.size());
5557 Result += " "; Result += VarName;
5558 Result += ProtocolName;
5559 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5560 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5561 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5562 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5563 ObjCPropertyDecl *PropDecl = Properties[i];
5564 if (i == 0)
5565 Result += "\t{{\"";
5566 else
5567 Result += "\t{\"";
5568 Result += PropDecl->getName(); Result += "\",";
5569 std::string PropertyTypeString, QuotePropertyTypeString;
5570 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5571 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5572 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5573 if (i == e-1)
5574 Result += "}}\n";
5575 else
5576 Result += "},\n";
5577 }
5578 Result += "};\n";
5579 }
5580}
5581
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005582// Metadata flags
5583enum MetaDataDlags {
5584 CLS = 0x0,
5585 CLS_META = 0x1,
5586 CLS_ROOT = 0x2,
5587 OBJC2_CLS_HIDDEN = 0x10,
5588 CLS_EXCEPTION = 0x20,
5589
5590 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5591 CLS_HAS_IVAR_RELEASER = 0x40,
5592 /// class was compiled with -fobjc-arr
5593 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5594};
5595
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005596static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5597 unsigned int flags,
5598 const std::string &InstanceStart,
5599 const std::string &InstanceSize,
5600 ArrayRef<ObjCMethodDecl *>baseMethods,
5601 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5602 ArrayRef<ObjCIvarDecl *>ivars,
5603 ArrayRef<ObjCPropertyDecl *>Properties,
5604 StringRef VarName,
5605 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005606 Result += "\nstatic struct _class_ro_t ";
5607 Result += VarName; Result += ClassName;
5608 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5609 Result += "\t";
5610 Result += llvm::utostr(flags); Result += ", ";
5611 Result += InstanceStart; Result += ", ";
5612 Result += InstanceSize; Result += ", \n";
5613 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005614 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5615 if (Triple.getArch() == llvm::Triple::x86_64)
5616 // uint32_t const reserved; // only when building for 64bit targets
5617 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005618 // const uint8_t * const ivarLayout;
5619 Result += "0, \n\t";
5620 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005621 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005622 if (baseMethods.size() > 0) {
5623 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005624 if (metaclass)
5625 Result += "_OBJC_$_CLASS_METHODS_";
5626 else
5627 Result += "_OBJC_$_INSTANCE_METHODS_";
5628 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005629 Result += ",\n\t";
5630 }
5631 else
5632 Result += "0, \n\t";
5633
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005634 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005635 Result += "(const struct _objc_protocol_list *)&";
5636 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5637 Result += ",\n\t";
5638 }
5639 else
5640 Result += "0, \n\t";
5641
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005642 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005643 Result += "(const struct _ivar_list_t *)&";
5644 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5645 Result += ",\n\t";
5646 }
5647 else
5648 Result += "0, \n\t";
5649
5650 // weakIvarLayout
5651 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005652 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005653 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005654 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005655 Result += ",\n";
5656 }
5657 else
5658 Result += "0, \n";
5659
5660 Result += "};\n";
5661}
5662
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005663static void Write_class_t(ASTContext *Context, std::string &Result,
5664 StringRef VarName,
5665 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005666
5667 if (metadata && !CDecl->getSuperClass()) {
5668 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005669 Result += "\n";
5670 if (CDecl->getImplementation())
5671 Result += "__declspec(dllexport) ";
5672 Result += "extern struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005673 Result += CDecl->getNameAsString();
5674 Result += ";\n";
5675 }
5676 // Also, for possibility of 'super' metadata class not having been defined yet.
5677 if (CDecl->getSuperClass()) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005678 Result += "\n";
5679 if (CDecl->getSuperClass()->getImplementation())
5680 Result += "__declspec(dllexport) ";
5681 Result += "extern struct _class_t ";
5682 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005683 Result += CDecl->getSuperClass()->getNameAsString();
5684 Result += ";\n";
5685 }
5686
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005687 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005688 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5689 Result += "\t";
5690 if (metadata) {
5691 if (CDecl->getSuperClass()) {
5692 Result += "&"; Result += VarName;
5693 Result += CDecl->getSuperClass()->getNameAsString();
5694 Result += ",\n\t";
5695 Result += "&"; Result += VarName;
5696 Result += CDecl->getSuperClass()->getNameAsString();
5697 Result += ",\n\t";
5698 }
5699 else {
5700 Result += "&"; Result += VarName;
5701 Result += CDecl->getNameAsString();
5702 Result += ",\n\t";
5703 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5704 Result += ",\n\t";
5705 }
5706 }
5707 else {
5708 Result += "&OBJC_METACLASS_$_";
5709 Result += CDecl->getNameAsString();
5710 Result += ",\n\t";
5711 if (CDecl->getSuperClass()) {
5712 Result += "&"; Result += VarName;
5713 Result += CDecl->getSuperClass()->getNameAsString();
5714 Result += ",\n\t";
5715 }
5716 else
5717 Result += "0,\n\t";
5718 }
5719 Result += "(void *)&_objc_empty_cache,\n\t";
5720 Result += "(void *)&_objc_empty_vtable,\n\t";
5721 if (metadata)
5722 Result += "&_OBJC_METACLASS_RO_$_";
5723 else
5724 Result += "&_OBJC_CLASS_RO_$_";
5725 Result += CDecl->getNameAsString();
5726 Result += ",\n};\n";
5727}
5728
Fariborz Jahanian61186122012-02-17 18:40:41 +00005729static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5730 std::string &Result,
5731 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005732 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005733 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5734 ArrayRef<ObjCMethodDecl *> ClassMethods,
5735 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5736 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005737
5738 StringRef ClassName = ClassDecl->getNameAsString();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005739 // must declare an extern class object in case this class is not implemented
5740 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005741 Result += "\n";
5742 if (ClassDecl->getImplementation())
5743 Result += "__declspec(dllexport) ";
5744
5745 Result += "extern struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005746 Result += "OBJC_CLASS_$_"; Result += ClassName;
5747 Result += ";\n";
5748
Fariborz Jahanian61186122012-02-17 18:40:41 +00005749 Result += "\nstatic struct _category_t ";
5750 Result += "_OBJC_$_CATEGORY_";
5751 Result += ClassName; Result += "_$_"; Result += CatName;
5752 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5753 Result += "{\n";
5754 Result += "\t\""; Result += ClassName; Result += "\",\n";
5755 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5756 Result += ",\n";
5757 if (InstanceMethods.size() > 0) {
5758 Result += "\t(const struct _method_list_t *)&";
5759 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5760 Result += ClassName; Result += "_$_"; Result += CatName;
5761 Result += ",\n";
5762 }
5763 else
5764 Result += "\t0,\n";
5765
5766 if (ClassMethods.size() > 0) {
5767 Result += "\t(const struct _method_list_t *)&";
5768 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5769 Result += ClassName; Result += "_$_"; Result += CatName;
5770 Result += ",\n";
5771 }
5772 else
5773 Result += "\t0,\n";
5774
5775 if (RefedProtocols.size() > 0) {
5776 Result += "\t(const struct _protocol_list_t *)&";
5777 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5778 Result += ClassName; Result += "_$_"; Result += CatName;
5779 Result += ",\n";
5780 }
5781 else
5782 Result += "\t0,\n";
5783
5784 if (ClassProperties.size() > 0) {
5785 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5786 Result += ClassName; Result += "_$_"; Result += CatName;
5787 Result += ",\n";
5788 }
5789 else
5790 Result += "\t0,\n";
5791
5792 Result += "};\n";
5793}
5794
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005795static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5796 ASTContext *Context, std::string &Result,
5797 ArrayRef<ObjCMethodDecl *> Methods,
5798 StringRef VarName,
5799 StringRef ProtocolName) {
5800 if (Methods.size() == 0)
5801 return;
5802
5803 Result += "\nstatic const char *";
5804 Result += VarName; Result += ProtocolName;
5805 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5806 Result += "{\n";
5807 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5808 ObjCMethodDecl *MD = Methods[i];
5809 std::string MethodTypeString, QuoteMethodTypeString;
5810 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5811 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5812 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5813 if (i == e-1)
5814 Result += "\n};\n";
5815 else {
5816 Result += ",\n";
5817 }
5818 }
5819}
5820
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005821static void Write_IvarOffsetVar(ASTContext *Context,
5822 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005823 ArrayRef<ObjCIvarDecl *> Ivars,
5824 StringRef VarName,
5825 StringRef ClassName) {
5826 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5827 // this is what happens:
5828 /**
5829 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5830 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5831 Class->getVisibility() == HiddenVisibility)
5832 Visibility shoud be: HiddenVisibility;
5833 else
5834 Visibility shoud be: DefaultVisibility;
5835 */
5836
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005837 Result += "\n";
5838 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5839 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005840 if (Context->getLangOpts().MicrosoftExt)
5841 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5842
5843 if (!Context->getLangOpts().MicrosoftExt ||
5844 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005845 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005846 Result += "unsigned long int ";
5847 else
5848 Result += "__declspec(dllexport) unsigned long int ";
5849
5850 Result += VarName;
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005851 Result += ClassName; Result += "_";
5852 Result += IvarDecl->getName();
5853 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5854 Result += " = ";
5855 if (IvarDecl->isBitField()) {
5856 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5857 // place all bitfields at offset 0.
5858 Result += "0;\n";
5859 }
5860 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005861 Result += "__OFFSETOFIVAR__(struct ";
5862 Result += ClassName;
5863 Result += "_IMPL, ";
5864 Result += IvarDecl->getName(); Result += ");\n";
5865 }
5866 }
5867}
5868
Fariborz Jahanianae932952012-02-10 20:47:10 +00005869static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5870 ASTContext *Context, std::string &Result,
5871 ArrayRef<ObjCIvarDecl *> Ivars,
5872 StringRef VarName,
5873 StringRef ClassName) {
5874 if (Ivars.size() > 0) {
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005875 Write_IvarOffsetVar(Context, Result, Ivars, "OBJC_IVAR_$_", ClassName);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005876
Fariborz Jahanianae932952012-02-10 20:47:10 +00005877 Result += "\nstatic ";
5878 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5879 Result += " "; Result += VarName;
5880 Result += ClassName;
5881 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5882 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5883 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5884 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5885 ObjCIvarDecl *IvarDecl = Ivars[i];
5886 if (i == 0)
5887 Result += "\t{{";
5888 else
5889 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005890
5891 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5892 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5893 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005894
5895 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5896 std::string IvarTypeString, QuoteIvarTypeString;
5897 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5898 IvarDecl);
5899 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5900 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5901
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005902 // FIXME. this alignment represents the host alignment and need be changed to
5903 // represent the target alignment.
5904 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5905 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005906 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005907 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5908 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005909 if (i == e-1)
5910 Result += "}}\n";
5911 else
5912 Result += "},\n";
5913 }
5914 Result += "};\n";
5915 }
5916}
5917
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005918/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005919void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5920 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005921
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005922 // Do not synthesize the protocol more than once.
5923 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5924 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005925 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005926
5927 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5928 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005929 // Must write out all protocol definitions in current qualifier list,
5930 // and in their nested qualifiers before writing out current definition.
5931 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5932 E = PDecl->protocol_end(); I != E; ++I)
5933 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005934
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005935 // Construct method lists.
5936 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5937 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5938 for (ObjCProtocolDecl::instmeth_iterator
5939 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5940 I != E; ++I) {
5941 ObjCMethodDecl *MD = *I;
5942 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5943 OptInstanceMethods.push_back(MD);
5944 } else {
5945 InstanceMethods.push_back(MD);
5946 }
5947 }
5948
5949 for (ObjCProtocolDecl::classmeth_iterator
5950 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5951 I != E; ++I) {
5952 ObjCMethodDecl *MD = *I;
5953 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5954 OptClassMethods.push_back(MD);
5955 } else {
5956 ClassMethods.push_back(MD);
5957 }
5958 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005959 std::vector<ObjCMethodDecl *> AllMethods;
5960 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5961 AllMethods.push_back(InstanceMethods[i]);
5962 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5963 AllMethods.push_back(ClassMethods[i]);
5964 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5965 AllMethods.push_back(OptInstanceMethods[i]);
5966 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5967 AllMethods.push_back(OptClassMethods[i]);
5968
5969 Write__extendedMethodTypes_initializer(*this, Context, Result,
5970 AllMethods,
5971 "_OBJC_PROTOCOL_METHOD_TYPES_",
5972 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005973 // Protocol's super protocol list
5974 std::vector<ObjCProtocolDecl *> SuperProtocols;
5975 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5976 E = PDecl->protocol_end(); I != E; ++I)
5977 SuperProtocols.push_back(*I);
5978
5979 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5980 "_OBJC_PROTOCOL_REFS_",
5981 PDecl->getNameAsString());
5982
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005983 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005984 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005985 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005986
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005987 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005988 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005989 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005990
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005991 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005992 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005993 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005994
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005995 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005996 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005997 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005998
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005999 // Protocol's property metadata.
6000 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6001 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6002 E = PDecl->prop_end(); I != E; ++I)
6003 ProtocolProperties.push_back(*I);
6004
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006005 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006006 /* Container */0,
6007 "_OBJC_PROTOCOL_PROPERTIES_",
6008 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006009
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006010 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006011 Result += "\n";
6012 if (LangOpts.MicrosoftExt)
6013 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006014 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006015 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006016 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6017 Result += "\t0,\n"; // id is; is null
6018 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006019 if (SuperProtocols.size() > 0) {
6020 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6021 Result += PDecl->getNameAsString(); Result += ",\n";
6022 }
6023 else
6024 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006025 if (InstanceMethods.size() > 0) {
6026 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6027 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006028 }
6029 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006030 Result += "\t0,\n";
6031
6032 if (ClassMethods.size() > 0) {
6033 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6034 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006035 }
6036 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006037 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006038
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006039 if (OptInstanceMethods.size() > 0) {
6040 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6041 Result += PDecl->getNameAsString(); Result += ",\n";
6042 }
6043 else
6044 Result += "\t0,\n";
6045
6046 if (OptClassMethods.size() > 0) {
6047 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6048 Result += PDecl->getNameAsString(); Result += ",\n";
6049 }
6050 else
6051 Result += "\t0,\n";
6052
6053 if (ProtocolProperties.size() > 0) {
6054 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6055 Result += PDecl->getNameAsString(); Result += ",\n";
6056 }
6057 else
6058 Result += "\t0,\n";
6059
6060 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6061 Result += "\t0,\n";
6062
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006063 if (AllMethods.size() > 0) {
6064 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6065 Result += PDecl->getNameAsString();
6066 Result += "\n};\n";
6067 }
6068 else
6069 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006070
6071 // Use this protocol meta-data to build protocol list table in section
6072 // .objc_protolist$B
6073 // Unspecified visibility means 'private extern'.
6074 if (LangOpts.MicrosoftExt)
6075 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6076 Result += "struct _protocol_t *";
6077 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6078 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6079 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006080
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006081 // Mark this protocol as having been generated.
6082 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6083 llvm_unreachable("protocol already synthesized");
6084
6085}
6086
6087void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6088 const ObjCList<ObjCProtocolDecl> &Protocols,
6089 StringRef prefix, StringRef ClassName,
6090 std::string &Result) {
6091 if (Protocols.empty()) return;
6092
6093 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006094 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006095
6096 // Output the top lovel protocol meta-data for the class.
6097 /* struct _objc_protocol_list {
6098 struct _objc_protocol_list *next;
6099 int protocol_count;
6100 struct _objc_protocol *class_protocols[];
6101 }
6102 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006103 Result += "\n";
6104 if (LangOpts.MicrosoftExt)
6105 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6106 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006107 Result += "\tstruct _objc_protocol_list *next;\n";
6108 Result += "\tint protocol_count;\n";
6109 Result += "\tstruct _objc_protocol *class_protocols[";
6110 Result += utostr(Protocols.size());
6111 Result += "];\n} _OBJC_";
6112 Result += prefix;
6113 Result += "_PROTOCOLS_";
6114 Result += ClassName;
6115 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6116 "{\n\t0, ";
6117 Result += utostr(Protocols.size());
6118 Result += "\n";
6119
6120 Result += "\t,{&_OBJC_PROTOCOL_";
6121 Result += Protocols[0]->getNameAsString();
6122 Result += " \n";
6123
6124 for (unsigned i = 1; i != Protocols.size(); i++) {
6125 Result += "\t ,&_OBJC_PROTOCOL_";
6126 Result += Protocols[i]->getNameAsString();
6127 Result += "\n";
6128 }
6129 Result += "\t }\n};\n";
6130}
6131
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006132/// hasObjCExceptionAttribute - Return true if this class or any super
6133/// class has the __objc_exception__ attribute.
6134/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6135static bool hasObjCExceptionAttribute(ASTContext &Context,
6136 const ObjCInterfaceDecl *OID) {
6137 if (OID->hasAttr<ObjCExceptionAttr>())
6138 return true;
6139 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6140 return hasObjCExceptionAttribute(Context, Super);
6141 return false;
6142}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006143
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006144void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6145 std::string &Result) {
6146 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6147
6148 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006149 if (CDecl->isImplicitInterfaceDecl())
6150 assert(false &&
6151 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006152
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006153 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006154 SmallVector<ObjCIvarDecl *, 8> IVars;
6155
6156 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6157 IVD; IVD = IVD->getNextIvar()) {
6158 // Ignore unnamed bit-fields.
6159 if (!IVD->getDeclName())
6160 continue;
6161 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006162 }
6163
Fariborz Jahanianae932952012-02-10 20:47:10 +00006164 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006165 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanianae932952012-02-10 20:47:10 +00006166 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006167
6168 // Build _objc_method_list for class's instance methods if needed
6169 SmallVector<ObjCMethodDecl *, 32>
6170 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6171
6172 // If any of our property implementations have associated getters or
6173 // setters, produce metadata for them as well.
6174 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6175 PropEnd = IDecl->propimpl_end();
6176 Prop != PropEnd; ++Prop) {
6177 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6178 continue;
6179 if (!(*Prop)->getPropertyIvarDecl())
6180 continue;
6181 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6182 if (!PD)
6183 continue;
6184 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6185 if (!Getter->isDefined())
6186 InstanceMethods.push_back(Getter);
6187 if (PD->isReadOnly())
6188 continue;
6189 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6190 if (!Setter->isDefined())
6191 InstanceMethods.push_back(Setter);
6192 }
6193
6194 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6195 "_OBJC_$_INSTANCE_METHODS_",
6196 IDecl->getNameAsString(), true);
6197
6198 SmallVector<ObjCMethodDecl *, 32>
6199 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6200
6201 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6202 "_OBJC_$_CLASS_METHODS_",
6203 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006204
6205 // Protocols referenced in class declaration?
6206 // Protocol's super protocol list
6207 std::vector<ObjCProtocolDecl *> RefedProtocols;
6208 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6209 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6210 E = Protocols.end();
6211 I != E; ++I) {
6212 RefedProtocols.push_back(*I);
6213 // Must write out all protocol definitions in current qualifier list,
6214 // and in their nested qualifiers before writing out current definition.
6215 RewriteObjCProtocolMetaData(*I, Result);
6216 }
6217
6218 Write_protocol_list_initializer(Context, Result,
6219 RefedProtocols,
6220 "_OBJC_CLASS_PROTOCOLS_$_",
6221 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006222
6223 // Protocol's property metadata.
6224 std::vector<ObjCPropertyDecl *> ClassProperties;
6225 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6226 E = CDecl->prop_end(); I != E; ++I)
6227 ClassProperties.push_back(*I);
6228
6229 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6230 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006231 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006232 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006233
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006234
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006235 // Data for initializing _class_ro_t metaclass meta-data
6236 uint32_t flags = CLS_META;
6237 std::string InstanceSize;
6238 std::string InstanceStart;
6239
6240
6241 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6242 if (classIsHidden)
6243 flags |= OBJC2_CLS_HIDDEN;
6244
6245 if (!CDecl->getSuperClass())
6246 // class is root
6247 flags |= CLS_ROOT;
6248 InstanceSize = "sizeof(struct _class_t)";
6249 InstanceStart = InstanceSize;
6250 Write__class_ro_t_initializer(Context, Result, flags,
6251 InstanceStart, InstanceSize,
6252 ClassMethods,
6253 0,
6254 0,
6255 0,
6256 "_OBJC_METACLASS_RO_$_",
6257 CDecl->getNameAsString());
6258
6259
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006260 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006261 flags = CLS;
6262 if (classIsHidden)
6263 flags |= OBJC2_CLS_HIDDEN;
6264
6265 if (hasObjCExceptionAttribute(*Context, CDecl))
6266 flags |= CLS_EXCEPTION;
6267
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006268 if (!CDecl->getSuperClass())
6269 // class is root
6270 flags |= CLS_ROOT;
6271
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006272 InstanceSize.clear();
6273 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006274 if (!ObjCSynthesizedStructs.count(CDecl)) {
6275 InstanceSize = "0";
6276 InstanceStart = "0";
6277 }
6278 else {
6279 InstanceSize = "sizeof(struct ";
6280 InstanceSize += CDecl->getNameAsString();
6281 InstanceSize += "_IMPL)";
6282
6283 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6284 if (IVD) {
6285 InstanceStart += "__OFFSETOFIVAR__(struct ";
6286 InstanceStart += CDecl->getNameAsString();
6287 InstanceStart += "_IMPL, ";
6288 InstanceStart += IVD->getNameAsString();
6289 InstanceStart += ")";
6290 }
6291 else
6292 InstanceStart = InstanceSize;
6293 }
6294 Write__class_ro_t_initializer(Context, Result, flags,
6295 InstanceStart, InstanceSize,
6296 InstanceMethods,
6297 RefedProtocols,
6298 IVars,
6299 ClassProperties,
6300 "_OBJC_CLASS_RO_$_",
6301 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006302
6303 Write_class_t(Context, Result,
6304 "OBJC_METACLASS_$_",
6305 CDecl, /*metaclass*/true);
6306
6307 Write_class_t(Context, Result,
6308 "OBJC_CLASS_$_",
6309 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006310
6311 if (ImplementationIsNonLazy(IDecl))
6312 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006313
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006314}
6315
6316void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6317 int ClsDefCount = ClassImplementation.size();
6318 int CatDefCount = CategoryImplementation.size();
6319
6320 // For each implemented class, write out all its meta data.
6321 for (int i = 0; i < ClsDefCount; i++)
6322 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6323
6324 // For each implemented category, write out all its meta data.
6325 for (int i = 0; i < CatDefCount; i++)
6326 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6327
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006328 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006329 if (LangOpts.MicrosoftExt)
6330 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006331 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6332 Result += llvm::utostr(ClsDefCount); Result += "]";
6333 Result +=
6334 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6335 "regular,no_dead_strip\")))= {\n";
6336 for (int i = 0; i < ClsDefCount; i++) {
6337 Result += "\t&OBJC_CLASS_$_";
6338 Result += ClassImplementation[i]->getNameAsString();
6339 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006340 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006341 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006342
6343 if (!DefinedNonLazyClasses.empty()) {
6344 if (LangOpts.MicrosoftExt)
6345 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6346 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6347 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6348 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6349 Result += ",\n";
6350 }
6351 Result += "};\n";
6352 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006353 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006354
6355 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006356 if (LangOpts.MicrosoftExt)
6357 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006358 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6359 Result += llvm::utostr(CatDefCount); Result += "]";
6360 Result +=
6361 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6362 "regular,no_dead_strip\")))= {\n";
6363 for (int i = 0; i < CatDefCount; i++) {
6364 Result += "\t&_OBJC_$_CATEGORY_";
6365 Result +=
6366 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6367 Result += "_$_";
6368 Result += CategoryImplementation[i]->getNameAsString();
6369 Result += ",\n";
6370 }
6371 Result += "};\n";
6372 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006373
6374 if (!DefinedNonLazyCategories.empty()) {
6375 if (LangOpts.MicrosoftExt)
6376 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6377 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6378 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6379 Result += "\t&_OBJC_$_CATEGORY_";
6380 Result +=
6381 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6382 Result += "_$_";
6383 Result += DefinedNonLazyCategories[i]->getNameAsString();
6384 Result += ",\n";
6385 }
6386 Result += "};\n";
6387 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006388}
6389
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006390void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6391 if (LangOpts.MicrosoftExt)
6392 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6393
6394 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6395 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006396 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006397}
6398
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006399/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6400/// implementation.
6401void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6402 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006403 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006404 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6405 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006406 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006407 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6408 CDecl = CDecl->getNextClassCategory())
6409 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6410 break;
6411
6412 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006413 FullCategoryName += "_$_";
6414 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006415
6416 // Build _objc_method_list for class's instance methods if needed
6417 SmallVector<ObjCMethodDecl *, 32>
6418 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6419
6420 // If any of our property implementations have associated getters or
6421 // setters, produce metadata for them as well.
6422 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6423 PropEnd = IDecl->propimpl_end();
6424 Prop != PropEnd; ++Prop) {
6425 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6426 continue;
6427 if (!(*Prop)->getPropertyIvarDecl())
6428 continue;
6429 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6430 if (!PD)
6431 continue;
6432 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6433 InstanceMethods.push_back(Getter);
6434 if (PD->isReadOnly())
6435 continue;
6436 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6437 InstanceMethods.push_back(Setter);
6438 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006439
Fariborz Jahanian61186122012-02-17 18:40:41 +00006440 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6441 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6442 FullCategoryName, true);
6443
6444 SmallVector<ObjCMethodDecl *, 32>
6445 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6446
6447 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6448 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6449 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006450
6451 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006452 // Protocol's super protocol list
6453 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006454 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6455 E = CDecl->protocol_end();
6456
6457 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006458 RefedProtocols.push_back(*I);
6459 // Must write out all protocol definitions in current qualifier list,
6460 // and in their nested qualifiers before writing out current definition.
6461 RewriteObjCProtocolMetaData(*I, Result);
6462 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006463
Fariborz Jahanian61186122012-02-17 18:40:41 +00006464 Write_protocol_list_initializer(Context, Result,
6465 RefedProtocols,
6466 "_OBJC_CATEGORY_PROTOCOLS_$_",
6467 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006468
Fariborz Jahanian61186122012-02-17 18:40:41 +00006469 // Protocol's property metadata.
6470 std::vector<ObjCPropertyDecl *> ClassProperties;
6471 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6472 E = CDecl->prop_end(); I != E; ++I)
6473 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006474
Fariborz Jahanian61186122012-02-17 18:40:41 +00006475 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6476 /* Container */0,
6477 "_OBJC_$_PROP_LIST_",
6478 FullCategoryName);
6479
6480 Write_category_t(*this, Context, Result,
6481 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006482 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006483 InstanceMethods,
6484 ClassMethods,
6485 RefedProtocols,
6486 ClassProperties);
6487
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006488 // Determine if this category is also "non-lazy".
6489 if (ImplementationIsNonLazy(IDecl))
6490 DefinedNonLazyCategories.push_back(CDecl);
6491
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006492}
6493
6494// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6495/// class methods.
6496template<typename MethodIterator>
6497void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6498 MethodIterator MethodEnd,
6499 bool IsInstanceMethod,
6500 StringRef prefix,
6501 StringRef ClassName,
6502 std::string &Result) {
6503 if (MethodBegin == MethodEnd) return;
6504
6505 if (!objc_impl_method) {
6506 /* struct _objc_method {
6507 SEL _cmd;
6508 char *method_types;
6509 void *_imp;
6510 }
6511 */
6512 Result += "\nstruct _objc_method {\n";
6513 Result += "\tSEL _cmd;\n";
6514 Result += "\tchar *method_types;\n";
6515 Result += "\tvoid *_imp;\n";
6516 Result += "};\n";
6517
6518 objc_impl_method = true;
6519 }
6520
6521 // Build _objc_method_list for class's methods if needed
6522
6523 /* struct {
6524 struct _objc_method_list *next_method;
6525 int method_count;
6526 struct _objc_method method_list[];
6527 }
6528 */
6529 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006530 Result += "\n";
6531 if (LangOpts.MicrosoftExt) {
6532 if (IsInstanceMethod)
6533 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6534 else
6535 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6536 }
6537 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006538 Result += "\tstruct _objc_method_list *next_method;\n";
6539 Result += "\tint method_count;\n";
6540 Result += "\tstruct _objc_method method_list[";
6541 Result += utostr(NumMethods);
6542 Result += "];\n} _OBJC_";
6543 Result += prefix;
6544 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6545 Result += "_METHODS_";
6546 Result += ClassName;
6547 Result += " __attribute__ ((used, section (\"__OBJC, __";
6548 Result += IsInstanceMethod ? "inst" : "cls";
6549 Result += "_meth\")))= ";
6550 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6551
6552 Result += "\t,{{(SEL)\"";
6553 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6554 std::string MethodTypeString;
6555 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6556 Result += "\", \"";
6557 Result += MethodTypeString;
6558 Result += "\", (void *)";
6559 Result += MethodInternalNames[*MethodBegin];
6560 Result += "}\n";
6561 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6562 Result += "\t ,{(SEL)\"";
6563 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6564 std::string MethodTypeString;
6565 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6566 Result += "\", \"";
6567 Result += MethodTypeString;
6568 Result += "\", (void *)";
6569 Result += MethodInternalNames[*MethodBegin];
6570 Result += "}\n";
6571 }
6572 Result += "\t }\n};\n";
6573}
6574
6575Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6576 SourceRange OldRange = IV->getSourceRange();
6577 Expr *BaseExpr = IV->getBase();
6578
6579 // Rewrite the base, but without actually doing replaces.
6580 {
6581 DisableReplaceStmtScope S(*this);
6582 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6583 IV->setBase(BaseExpr);
6584 }
6585
6586 ObjCIvarDecl *D = IV->getDecl();
6587
6588 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006589
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006590 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6591 const ObjCInterfaceType *iFaceDecl =
6592 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6593 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6594 // lookup which class implements the instance variable.
6595 ObjCInterfaceDecl *clsDeclared = 0;
6596 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6597 clsDeclared);
6598 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6599
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006600 // Build name of symbol holding ivar offset.
6601 std::string IvarOffsetName = "OBJC_IVAR_$_";
6602 IvarOffsetName += clsDeclared->getIdentifier()->getName();
6603 IvarOffsetName += "_";
6604 IvarOffsetName += D->getName();
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006605 ReferencedIvars[clsDeclared].insert(D);
6606
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006607 // cast offset to "char *".
6608 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6609 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006610 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006611 BaseExpr);
6612 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6613 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6614 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006615 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6616 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006617 SourceLocation());
6618 BinaryOperator *addExpr =
6619 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6620 Context->getPointerType(Context->CharTy),
6621 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006622 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006623 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6624 SourceLocation(),
6625 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006626 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006627 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006628 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006629
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006630 castExpr = NoTypeInfoCStyleCastExpr(Context,
6631 castT,
6632 CK_BitCast,
6633 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006634 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006635 VK_LValue, OK_Ordinary,
6636 SourceLocation());
6637 PE = new (Context) ParenExpr(OldRange.getBegin(),
6638 OldRange.getEnd(),
6639 Exp);
6640
6641 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006642 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006643
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006644 ReplaceStmtWithRange(IV, Replacement, OldRange);
6645 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006646}