blob: 1081b9df9000d1ca4a8626973f4eed93a8a84768 [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
1685/// RewriteObjCSynchronizedStmt -
1686/// This routine rewrites @synchronized(expr) stmt;
1687/// into:
1688/// objc_sync_enter(expr);
1689/// @try stmt @finally { objc_sync_exit(expr); }
1690///
1691Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1692 // Get the start location and compute the semi location.
1693 SourceLocation startLoc = S->getLocStart();
1694 const char *startBuf = SM->getCharacterData(startLoc);
1695
1696 assert((*startBuf == '@') && "bogus @synchronized location");
1697
1698 std::string buf;
1699 buf = "objc_sync_enter((id)";
1700 const char *lparenBuf = startBuf;
1701 while (*lparenBuf != '(') lparenBuf++;
1702 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1703 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1704 // the sync expression is typically a message expression that's already
1705 // been rewritten! (which implies the SourceLocation's are invalid).
1706 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1707 const char *endBuf = SM->getCharacterData(endLoc);
1708 while (*endBuf != ')') endBuf--;
1709 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1710 buf = ");\n";
1711 // declare a new scope with two variables, _stack and _rethrow.
1712 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1713 buf += "int buf[18/*32-bit i386*/];\n";
1714 buf += "char *pointers[4];} _stack;\n";
1715 buf += "id volatile _rethrow = 0;\n";
1716 buf += "objc_exception_try_enter(&_stack);\n";
1717 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1718 ReplaceText(rparenLoc, 1, buf);
1719 startLoc = S->getSynchBody()->getLocEnd();
1720 startBuf = SM->getCharacterData(startLoc);
1721
1722 assert((*startBuf == '}') && "bogus @synchronized block");
1723 SourceLocation lastCurlyLoc = startLoc;
1724 buf = "}\nelse {\n";
1725 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1726 buf += "}\n";
1727 buf += "{ /* implicit finally clause */\n";
1728 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1729
1730 std::string syncBuf;
1731 syncBuf += " objc_sync_exit(";
1732
1733 Expr *syncExpr = S->getSynchExpr();
1734 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1735 ? CK_BitCast :
1736 syncExpr->getType()->isBlockPointerType()
1737 ? CK_BlockPointerToObjCPointerCast
1738 : CK_CPointerToObjCPointerCast;
1739 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1740 CK, syncExpr);
1741 std::string syncExprBufS;
1742 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1743 syncExpr->printPretty(syncExprBuf, *Context, 0,
1744 PrintingPolicy(LangOpts));
1745 syncBuf += syncExprBuf.str();
1746 syncBuf += ");";
1747
1748 buf += syncBuf;
1749 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1750 buf += "}\n";
1751 buf += "}";
1752
1753 ReplaceText(lastCurlyLoc, 1, buf);
1754
1755 bool hasReturns = false;
1756 HasReturnStmts(S->getSynchBody(), hasReturns);
1757 if (hasReturns)
1758 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1759
1760 return 0;
1761}
1762
1763void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1764{
1765 // Perform a bottom up traversal of all children.
1766 for (Stmt::child_range CI = S->children(); CI; ++CI)
1767 if (*CI)
1768 WarnAboutReturnGotoStmts(*CI);
1769
1770 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1771 Diags.Report(Context->getFullLoc(S->getLocStart()),
1772 TryFinallyContainsReturnDiag);
1773 }
1774 return;
1775}
1776
1777void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1778{
1779 // Perform a bottom up traversal of all children.
1780 for (Stmt::child_range CI = S->children(); CI; ++CI)
1781 if (*CI)
1782 HasReturnStmts(*CI, hasReturns);
1783
1784 if (isa<ReturnStmt>(S))
1785 hasReturns = true;
1786 return;
1787}
1788
1789void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1790 // Perform a bottom up traversal of all children.
1791 for (Stmt::child_range CI = S->children(); CI; ++CI)
1792 if (*CI) {
1793 RewriteTryReturnStmts(*CI);
1794 }
1795 if (isa<ReturnStmt>(S)) {
1796 SourceLocation startLoc = S->getLocStart();
1797 const char *startBuf = SM->getCharacterData(startLoc);
1798
1799 const char *semiBuf = strchr(startBuf, ';');
1800 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1801 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1802
1803 std::string buf;
1804 buf = "{ objc_exception_try_exit(&_stack); return";
1805
1806 ReplaceText(startLoc, 6, buf);
1807 InsertText(onePastSemiLoc, "}");
1808 }
1809 return;
1810}
1811
1812void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1813 // Perform a bottom up traversal of all children.
1814 for (Stmt::child_range CI = S->children(); CI; ++CI)
1815 if (*CI) {
1816 RewriteSyncReturnStmts(*CI, syncExitBuf);
1817 }
1818 if (isa<ReturnStmt>(S)) {
1819 SourceLocation startLoc = S->getLocStart();
1820 const char *startBuf = SM->getCharacterData(startLoc);
1821
1822 const char *semiBuf = strchr(startBuf, ';');
1823 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1824 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1825
1826 std::string buf;
1827 buf = "{ objc_exception_try_exit(&_stack);";
1828 buf += syncExitBuf;
1829 buf += " return";
1830
1831 ReplaceText(startLoc, 6, buf);
1832 InsertText(onePastSemiLoc, "}");
1833 }
1834 return;
1835}
1836
1837Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001838 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001839 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001840 std::string buf;
1841
1842 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001843 if (noCatch)
1844 buf = "{ id volatile _rethrow = 0;\n";
1845 else {
1846 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1847 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001848 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001849 // Get the start location and compute the semi location.
1850 SourceLocation startLoc = S->getLocStart();
1851 const char *startBuf = SM->getCharacterData(startLoc);
1852
1853 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001854 if (finalStmt)
1855 ReplaceText(startLoc, 1, buf);
1856 else
1857 // @try -> try
1858 ReplaceText(startLoc, 1, "");
1859
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001860 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1861 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001862 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001863
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001864 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001865 bool AtRemoved = false;
1866 if (catchDecl) {
1867 QualType t = catchDecl->getType();
1868 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1869 // Should be a pointer to a class.
1870 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1871 if (IDecl) {
1872 std::string Result;
1873 startBuf = SM->getCharacterData(startLoc);
1874 assert((*startBuf == '@') && "bogus @catch location");
1875 SourceLocation rParenLoc = Catch->getRParenLoc();
1876 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1877
1878 // _objc_exc_Foo *_e as argument to catch.
1879 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1880 Result += " *_"; Result += catchDecl->getNameAsString();
1881 Result += ")";
1882 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1883 // Foo *e = (Foo *)_e;
1884 Result.clear();
1885 Result = "{ ";
1886 Result += IDecl->getNameAsString();
1887 Result += " *"; Result += catchDecl->getNameAsString();
1888 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1889 Result += "_"; Result += catchDecl->getNameAsString();
1890
1891 Result += "; ";
1892 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1893 ReplaceText(lBraceLoc, 1, Result);
1894 AtRemoved = true;
1895 }
1896 }
1897 }
1898 if (!AtRemoved)
1899 // @catch -> catch
1900 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001901
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001902 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001903 if (finalStmt) {
1904 buf.clear();
1905 if (noCatch)
1906 buf = "catch (id e) {_rethrow = e;}\n";
1907 else
1908 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1909
1910 SourceLocation startFinalLoc = finalStmt->getLocStart();
1911 ReplaceText(startFinalLoc, 8, buf);
1912 Stmt *body = finalStmt->getFinallyBody();
1913 SourceLocation startFinalBodyLoc = body->getLocStart();
1914 buf.clear();
1915 buf = "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1916 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1917 buf += "\tid rethrow;\n";
1918 buf += "\t} _fin_force_rethow(_rethrow);";
1919 ReplaceText(startFinalBodyLoc, 1, buf);
1920
1921 SourceLocation endFinalBodyLoc = body->getLocEnd();
1922 ReplaceText(endFinalBodyLoc, 1, "}\n}");
1923 }
1924
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001925 return 0;
1926}
1927
1928// This can't be done with ReplaceStmt(S, ThrowExpr), since
1929// the throw expression is typically a message expression that's already
1930// been rewritten! (which implies the SourceLocation's are invalid).
1931Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1932 // Get the start location and compute the semi location.
1933 SourceLocation startLoc = S->getLocStart();
1934 const char *startBuf = SM->getCharacterData(startLoc);
1935
1936 assert((*startBuf == '@') && "bogus @throw location");
1937
1938 std::string buf;
1939 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1940 if (S->getThrowExpr())
1941 buf = "objc_exception_throw(";
1942 else // add an implicit argument
1943 buf = "objc_exception_throw(_caught";
1944
1945 // handle "@ throw" correctly.
1946 const char *wBuf = strchr(startBuf, 'w');
1947 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1948 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1949
1950 const char *semiBuf = strchr(startBuf, ';');
1951 assert((*semiBuf == ';') && "@throw: can't find ';'");
1952 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1953 ReplaceText(semiLoc, 1, ");");
1954 return 0;
1955}
1956
1957Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1958 // Create a new string expression.
1959 QualType StrType = Context->getPointerType(Context->CharTy);
1960 std::string StrEncoding;
1961 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1962 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1963 StringLiteral::Ascii, false,
1964 StrType, SourceLocation());
1965 ReplaceStmt(Exp, Replacement);
1966
1967 // Replace this subexpr in the parent.
1968 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1969 return Replacement;
1970}
1971
1972Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1973 if (!SelGetUidFunctionDecl)
1974 SynthSelGetUidFunctionDecl();
1975 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1976 // Create a call to sel_registerName("selName").
1977 SmallVector<Expr*, 8> SelExprs;
1978 QualType argType = Context->getPointerType(Context->CharTy);
1979 SelExprs.push_back(StringLiteral::Create(*Context,
1980 Exp->getSelector().getAsString(),
1981 StringLiteral::Ascii, false,
1982 argType, SourceLocation()));
1983 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1984 &SelExprs[0], SelExprs.size());
1985 ReplaceStmt(Exp, SelExp);
1986 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1987 return SelExp;
1988}
1989
1990CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1991 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1992 SourceLocation EndLoc) {
1993 // Get the type, we will need to reference it in a couple spots.
1994 QualType msgSendType = FD->getType();
1995
1996 // Create a reference to the objc_msgSend() declaration.
1997 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001998 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001999
2000 // Now, we cast the reference to a pointer to the objc_msgSend type.
2001 QualType pToFunc = Context->getPointerType(msgSendType);
2002 ImplicitCastExpr *ICE =
2003 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2004 DRE, 0, VK_RValue);
2005
2006 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2007
2008 CallExpr *Exp =
2009 new (Context) CallExpr(*Context, ICE, args, nargs,
2010 FT->getCallResultType(*Context),
2011 VK_RValue, EndLoc);
2012 return Exp;
2013}
2014
2015static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2016 const char *&startRef, const char *&endRef) {
2017 while (startBuf < endBuf) {
2018 if (*startBuf == '<')
2019 startRef = startBuf; // mark the start.
2020 if (*startBuf == '>') {
2021 if (startRef && *startRef == '<') {
2022 endRef = startBuf; // mark the end.
2023 return true;
2024 }
2025 return false;
2026 }
2027 startBuf++;
2028 }
2029 return false;
2030}
2031
2032static void scanToNextArgument(const char *&argRef) {
2033 int angle = 0;
2034 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2035 if (*argRef == '<')
2036 angle++;
2037 else if (*argRef == '>')
2038 angle--;
2039 argRef++;
2040 }
2041 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2042}
2043
2044bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2045 if (T->isObjCQualifiedIdType())
2046 return true;
2047 if (const PointerType *PT = T->getAs<PointerType>()) {
2048 if (PT->getPointeeType()->isObjCQualifiedIdType())
2049 return true;
2050 }
2051 if (T->isObjCObjectPointerType()) {
2052 T = T->getPointeeType();
2053 return T->isObjCQualifiedInterfaceType();
2054 }
2055 if (T->isArrayType()) {
2056 QualType ElemTy = Context->getBaseElementType(T);
2057 return needToScanForQualifiers(ElemTy);
2058 }
2059 return false;
2060}
2061
2062void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2063 QualType Type = E->getType();
2064 if (needToScanForQualifiers(Type)) {
2065 SourceLocation Loc, EndLoc;
2066
2067 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2068 Loc = ECE->getLParenLoc();
2069 EndLoc = ECE->getRParenLoc();
2070 } else {
2071 Loc = E->getLocStart();
2072 EndLoc = E->getLocEnd();
2073 }
2074 // This will defend against trying to rewrite synthesized expressions.
2075 if (Loc.isInvalid() || EndLoc.isInvalid())
2076 return;
2077
2078 const char *startBuf = SM->getCharacterData(Loc);
2079 const char *endBuf = SM->getCharacterData(EndLoc);
2080 const char *startRef = 0, *endRef = 0;
2081 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2082 // Get the locations of the startRef, endRef.
2083 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2084 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2085 // Comment out the protocol references.
2086 InsertText(LessLoc, "/*");
2087 InsertText(GreaterLoc, "*/");
2088 }
2089 }
2090}
2091
2092void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2093 SourceLocation Loc;
2094 QualType Type;
2095 const FunctionProtoType *proto = 0;
2096 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2097 Loc = VD->getLocation();
2098 Type = VD->getType();
2099 }
2100 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2101 Loc = FD->getLocation();
2102 // Check for ObjC 'id' and class types that have been adorned with protocol
2103 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2104 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2105 assert(funcType && "missing function type");
2106 proto = dyn_cast<FunctionProtoType>(funcType);
2107 if (!proto)
2108 return;
2109 Type = proto->getResultType();
2110 }
2111 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2112 Loc = FD->getLocation();
2113 Type = FD->getType();
2114 }
2115 else
2116 return;
2117
2118 if (needToScanForQualifiers(Type)) {
2119 // Since types are unique, we need to scan the buffer.
2120
2121 const char *endBuf = SM->getCharacterData(Loc);
2122 const char *startBuf = endBuf;
2123 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2124 startBuf--; // scan backward (from the decl location) for return type.
2125 const char *startRef = 0, *endRef = 0;
2126 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2127 // Get the locations of the startRef, endRef.
2128 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2129 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2130 // Comment out the protocol references.
2131 InsertText(LessLoc, "/*");
2132 InsertText(GreaterLoc, "*/");
2133 }
2134 }
2135 if (!proto)
2136 return; // most likely, was a variable
2137 // Now check arguments.
2138 const char *startBuf = SM->getCharacterData(Loc);
2139 const char *startFuncBuf = startBuf;
2140 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2141 if (needToScanForQualifiers(proto->getArgType(i))) {
2142 // Since types are unique, we need to scan the buffer.
2143
2144 const char *endBuf = startBuf;
2145 // scan forward (from the decl location) for argument types.
2146 scanToNextArgument(endBuf);
2147 const char *startRef = 0, *endRef = 0;
2148 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2149 // Get the locations of the startRef, endRef.
2150 SourceLocation LessLoc =
2151 Loc.getLocWithOffset(startRef-startFuncBuf);
2152 SourceLocation GreaterLoc =
2153 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2154 // Comment out the protocol references.
2155 InsertText(LessLoc, "/*");
2156 InsertText(GreaterLoc, "*/");
2157 }
2158 startBuf = ++endBuf;
2159 }
2160 else {
2161 // If the function name is derived from a macro expansion, then the
2162 // argument buffer will not follow the name. Need to speak with Chris.
2163 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2164 startBuf++; // scan forward (from the decl location) for argument types.
2165 startBuf++;
2166 }
2167 }
2168}
2169
2170void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2171 QualType QT = ND->getType();
2172 const Type* TypePtr = QT->getAs<Type>();
2173 if (!isa<TypeOfExprType>(TypePtr))
2174 return;
2175 while (isa<TypeOfExprType>(TypePtr)) {
2176 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2177 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2178 TypePtr = QT->getAs<Type>();
2179 }
2180 // FIXME. This will not work for multiple declarators; as in:
2181 // __typeof__(a) b,c,d;
2182 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2183 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2184 const char *startBuf = SM->getCharacterData(DeclLoc);
2185 if (ND->getInit()) {
2186 std::string Name(ND->getNameAsString());
2187 TypeAsString += " " + Name + " = ";
2188 Expr *E = ND->getInit();
2189 SourceLocation startLoc;
2190 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2191 startLoc = ECE->getLParenLoc();
2192 else
2193 startLoc = E->getLocStart();
2194 startLoc = SM->getExpansionLoc(startLoc);
2195 const char *endBuf = SM->getCharacterData(startLoc);
2196 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2197 }
2198 else {
2199 SourceLocation X = ND->getLocEnd();
2200 X = SM->getExpansionLoc(X);
2201 const char *endBuf = SM->getCharacterData(X);
2202 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2203 }
2204}
2205
2206// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2207void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2208 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2209 SmallVector<QualType, 16> ArgTys;
2210 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2211 QualType getFuncType =
2212 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2213 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2214 SourceLocation(),
2215 SourceLocation(),
2216 SelGetUidIdent, getFuncType, 0,
2217 SC_Extern,
2218 SC_None, false);
2219}
2220
2221void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2222 // declared in <objc/objc.h>
2223 if (FD->getIdentifier() &&
2224 FD->getName() == "sel_registerName") {
2225 SelGetUidFunctionDecl = FD;
2226 return;
2227 }
2228 RewriteObjCQualifiedInterfaceTypes(FD);
2229}
2230
2231void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2232 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2233 const char *argPtr = TypeString.c_str();
2234 if (!strchr(argPtr, '^')) {
2235 Str += TypeString;
2236 return;
2237 }
2238 while (*argPtr) {
2239 Str += (*argPtr == '^' ? '*' : *argPtr);
2240 argPtr++;
2241 }
2242}
2243
2244// FIXME. Consolidate this routine with RewriteBlockPointerType.
2245void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2246 ValueDecl *VD) {
2247 QualType Type = VD->getType();
2248 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2249 const char *argPtr = TypeString.c_str();
2250 int paren = 0;
2251 while (*argPtr) {
2252 switch (*argPtr) {
2253 case '(':
2254 Str += *argPtr;
2255 paren++;
2256 break;
2257 case ')':
2258 Str += *argPtr;
2259 paren--;
2260 break;
2261 case '^':
2262 Str += '*';
2263 if (paren == 1)
2264 Str += VD->getNameAsString();
2265 break;
2266 default:
2267 Str += *argPtr;
2268 break;
2269 }
2270 argPtr++;
2271 }
2272}
2273
2274
2275void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2276 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2277 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2278 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2279 if (!proto)
2280 return;
2281 QualType Type = proto->getResultType();
2282 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2283 FdStr += " ";
2284 FdStr += FD->getName();
2285 FdStr += "(";
2286 unsigned numArgs = proto->getNumArgs();
2287 for (unsigned i = 0; i < numArgs; i++) {
2288 QualType ArgType = proto->getArgType(i);
2289 RewriteBlockPointerType(FdStr, ArgType);
2290 if (i+1 < numArgs)
2291 FdStr += ", ";
2292 }
2293 FdStr += ");\n";
2294 InsertText(FunLocStart, FdStr);
2295 CurFunctionDeclToDeclareForBlock = 0;
2296}
2297
2298// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2299void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2300 if (SuperContructorFunctionDecl)
2301 return;
2302 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2303 SmallVector<QualType, 16> ArgTys;
2304 QualType argT = Context->getObjCIdType();
2305 assert(!argT.isNull() && "Can't find 'id' type");
2306 ArgTys.push_back(argT);
2307 ArgTys.push_back(argT);
2308 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2309 &ArgTys[0], ArgTys.size());
2310 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2311 SourceLocation(),
2312 SourceLocation(),
2313 msgSendIdent, msgSendType, 0,
2314 SC_Extern,
2315 SC_None, false);
2316}
2317
2318// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2319void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2320 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2321 SmallVector<QualType, 16> ArgTys;
2322 QualType argT = Context->getObjCIdType();
2323 assert(!argT.isNull() && "Can't find 'id' type");
2324 ArgTys.push_back(argT);
2325 argT = Context->getObjCSelType();
2326 assert(!argT.isNull() && "Can't find 'SEL' type");
2327 ArgTys.push_back(argT);
2328 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2329 &ArgTys[0], ArgTys.size(),
2330 true /*isVariadic*/);
2331 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2332 SourceLocation(),
2333 SourceLocation(),
2334 msgSendIdent, msgSendType, 0,
2335 SC_Extern,
2336 SC_None, false);
2337}
2338
2339// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2340void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2341 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2342 SmallVector<QualType, 16> ArgTys;
2343 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2344 SourceLocation(), SourceLocation(),
2345 &Context->Idents.get("objc_super"));
2346 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2347 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2348 ArgTys.push_back(argT);
2349 argT = Context->getObjCSelType();
2350 assert(!argT.isNull() && "Can't find 'SEL' type");
2351 ArgTys.push_back(argT);
2352 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2353 &ArgTys[0], ArgTys.size(),
2354 true /*isVariadic*/);
2355 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2356 SourceLocation(),
2357 SourceLocation(),
2358 msgSendIdent, msgSendType, 0,
2359 SC_Extern,
2360 SC_None, false);
2361}
2362
2363// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2364void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2365 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2366 SmallVector<QualType, 16> ArgTys;
2367 QualType argT = Context->getObjCIdType();
2368 assert(!argT.isNull() && "Can't find 'id' type");
2369 ArgTys.push_back(argT);
2370 argT = Context->getObjCSelType();
2371 assert(!argT.isNull() && "Can't find 'SEL' type");
2372 ArgTys.push_back(argT);
2373 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2374 &ArgTys[0], ArgTys.size(),
2375 true /*isVariadic*/);
2376 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2377 SourceLocation(),
2378 SourceLocation(),
2379 msgSendIdent, msgSendType, 0,
2380 SC_Extern,
2381 SC_None, false);
2382}
2383
2384// SynthMsgSendSuperStretFunctionDecl -
2385// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2386void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2387 IdentifierInfo *msgSendIdent =
2388 &Context->Idents.get("objc_msgSendSuper_stret");
2389 SmallVector<QualType, 16> ArgTys;
2390 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2391 SourceLocation(), SourceLocation(),
2392 &Context->Idents.get("objc_super"));
2393 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2394 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2395 ArgTys.push_back(argT);
2396 argT = Context->getObjCSelType();
2397 assert(!argT.isNull() && "Can't find 'SEL' type");
2398 ArgTys.push_back(argT);
2399 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2400 &ArgTys[0], ArgTys.size(),
2401 true /*isVariadic*/);
2402 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2403 SourceLocation(),
2404 SourceLocation(),
2405 msgSendIdent, msgSendType, 0,
2406 SC_Extern,
2407 SC_None, false);
2408}
2409
2410// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2411void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2412 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2413 SmallVector<QualType, 16> ArgTys;
2414 QualType argT = Context->getObjCIdType();
2415 assert(!argT.isNull() && "Can't find 'id' type");
2416 ArgTys.push_back(argT);
2417 argT = Context->getObjCSelType();
2418 assert(!argT.isNull() && "Can't find 'SEL' type");
2419 ArgTys.push_back(argT);
2420 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2421 &ArgTys[0], ArgTys.size(),
2422 true /*isVariadic*/);
2423 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2424 SourceLocation(),
2425 SourceLocation(),
2426 msgSendIdent, msgSendType, 0,
2427 SC_Extern,
2428 SC_None, false);
2429}
2430
2431// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2432void RewriteModernObjC::SynthGetClassFunctionDecl() {
2433 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2434 SmallVector<QualType, 16> ArgTys;
2435 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2436 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2437 &ArgTys[0], ArgTys.size());
2438 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2439 SourceLocation(),
2440 SourceLocation(),
2441 getClassIdent, getClassType, 0,
2442 SC_Extern,
2443 SC_None, false);
2444}
2445
2446// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2447void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2448 IdentifierInfo *getSuperClassIdent =
2449 &Context->Idents.get("class_getSuperclass");
2450 SmallVector<QualType, 16> ArgTys;
2451 ArgTys.push_back(Context->getObjCClassType());
2452 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2453 &ArgTys[0], ArgTys.size());
2454 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2455 SourceLocation(),
2456 SourceLocation(),
2457 getSuperClassIdent,
2458 getClassType, 0,
2459 SC_Extern,
2460 SC_None,
2461 false);
2462}
2463
2464// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2465void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2466 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2467 SmallVector<QualType, 16> ArgTys;
2468 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2469 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2470 &ArgTys[0], ArgTys.size());
2471 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2472 SourceLocation(),
2473 SourceLocation(),
2474 getClassIdent, getClassType, 0,
2475 SC_Extern,
2476 SC_None, false);
2477}
2478
2479Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2480 QualType strType = getConstantStringStructType();
2481
2482 std::string S = "__NSConstantStringImpl_";
2483
2484 std::string tmpName = InFileName;
2485 unsigned i;
2486 for (i=0; i < tmpName.length(); i++) {
2487 char c = tmpName.at(i);
2488 // replace any non alphanumeric characters with '_'.
2489 if (!isalpha(c) && (c < '0' || c > '9'))
2490 tmpName[i] = '_';
2491 }
2492 S += tmpName;
2493 S += "_";
2494 S += utostr(NumObjCStringLiterals++);
2495
2496 Preamble += "static __NSConstantStringImpl " + S;
2497 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2498 Preamble += "0x000007c8,"; // utf8_str
2499 // The pretty printer for StringLiteral handles escape characters properly.
2500 std::string prettyBufS;
2501 llvm::raw_string_ostream prettyBuf(prettyBufS);
2502 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2503 PrintingPolicy(LangOpts));
2504 Preamble += prettyBuf.str();
2505 Preamble += ",";
2506 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2507
2508 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2509 SourceLocation(), &Context->Idents.get(S),
2510 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002511 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002512 SourceLocation());
2513 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2514 Context->getPointerType(DRE->getType()),
2515 VK_RValue, OK_Ordinary,
2516 SourceLocation());
2517 // cast to NSConstantString *
2518 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2519 CK_CPointerToObjCPointerCast, Unop);
2520 ReplaceStmt(Exp, cast);
2521 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2522 return cast;
2523}
2524
2525// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2526QualType RewriteModernObjC::getSuperStructType() {
2527 if (!SuperStructDecl) {
2528 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2529 SourceLocation(), SourceLocation(),
2530 &Context->Idents.get("objc_super"));
2531 QualType FieldTypes[2];
2532
2533 // struct objc_object *receiver;
2534 FieldTypes[0] = Context->getObjCIdType();
2535 // struct objc_class *super;
2536 FieldTypes[1] = Context->getObjCClassType();
2537
2538 // Create fields
2539 for (unsigned i = 0; i < 2; ++i) {
2540 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2541 SourceLocation(),
2542 SourceLocation(), 0,
2543 FieldTypes[i], 0,
2544 /*BitWidth=*/0,
2545 /*Mutable=*/false,
2546 /*HasInit=*/false));
2547 }
2548
2549 SuperStructDecl->completeDefinition();
2550 }
2551 return Context->getTagDeclType(SuperStructDecl);
2552}
2553
2554QualType RewriteModernObjC::getConstantStringStructType() {
2555 if (!ConstantStringDecl) {
2556 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2557 SourceLocation(), SourceLocation(),
2558 &Context->Idents.get("__NSConstantStringImpl"));
2559 QualType FieldTypes[4];
2560
2561 // struct objc_object *receiver;
2562 FieldTypes[0] = Context->getObjCIdType();
2563 // int flags;
2564 FieldTypes[1] = Context->IntTy;
2565 // char *str;
2566 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2567 // long length;
2568 FieldTypes[3] = Context->LongTy;
2569
2570 // Create fields
2571 for (unsigned i = 0; i < 4; ++i) {
2572 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2573 ConstantStringDecl,
2574 SourceLocation(),
2575 SourceLocation(), 0,
2576 FieldTypes[i], 0,
2577 /*BitWidth=*/0,
2578 /*Mutable=*/true,
2579 /*HasInit=*/false));
2580 }
2581
2582 ConstantStringDecl->completeDefinition();
2583 }
2584 return Context->getTagDeclType(ConstantStringDecl);
2585}
2586
2587Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2588 SourceLocation StartLoc,
2589 SourceLocation EndLoc) {
2590 if (!SelGetUidFunctionDecl)
2591 SynthSelGetUidFunctionDecl();
2592 if (!MsgSendFunctionDecl)
2593 SynthMsgSendFunctionDecl();
2594 if (!MsgSendSuperFunctionDecl)
2595 SynthMsgSendSuperFunctionDecl();
2596 if (!MsgSendStretFunctionDecl)
2597 SynthMsgSendStretFunctionDecl();
2598 if (!MsgSendSuperStretFunctionDecl)
2599 SynthMsgSendSuperStretFunctionDecl();
2600 if (!MsgSendFpretFunctionDecl)
2601 SynthMsgSendFpretFunctionDecl();
2602 if (!GetClassFunctionDecl)
2603 SynthGetClassFunctionDecl();
2604 if (!GetSuperClassFunctionDecl)
2605 SynthGetSuperClassFunctionDecl();
2606 if (!GetMetaClassFunctionDecl)
2607 SynthGetMetaClassFunctionDecl();
2608
2609 // default to objc_msgSend().
2610 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2611 // May need to use objc_msgSend_stret() as well.
2612 FunctionDecl *MsgSendStretFlavor = 0;
2613 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2614 QualType resultType = mDecl->getResultType();
2615 if (resultType->isRecordType())
2616 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2617 else if (resultType->isRealFloatingType())
2618 MsgSendFlavor = MsgSendFpretFunctionDecl;
2619 }
2620
2621 // Synthesize a call to objc_msgSend().
2622 SmallVector<Expr*, 8> MsgExprs;
2623 switch (Exp->getReceiverKind()) {
2624 case ObjCMessageExpr::SuperClass: {
2625 MsgSendFlavor = MsgSendSuperFunctionDecl;
2626 if (MsgSendStretFlavor)
2627 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2628 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2629
2630 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2631
2632 SmallVector<Expr*, 4> InitExprs;
2633
2634 // set the receiver to self, the first argument to all methods.
2635 InitExprs.push_back(
2636 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2637 CK_BitCast,
2638 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002639 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002640 Context->getObjCIdType(),
2641 VK_RValue,
2642 SourceLocation()))
2643 ); // set the 'receiver'.
2644
2645 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2646 SmallVector<Expr*, 8> ClsExprs;
2647 QualType argType = Context->getPointerType(Context->CharTy);
2648 ClsExprs.push_back(StringLiteral::Create(*Context,
2649 ClassDecl->getIdentifier()->getName(),
2650 StringLiteral::Ascii, false,
2651 argType, SourceLocation()));
2652 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2653 &ClsExprs[0],
2654 ClsExprs.size(),
2655 StartLoc,
2656 EndLoc);
2657 // (Class)objc_getClass("CurrentClass")
2658 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2659 Context->getObjCClassType(),
2660 CK_BitCast, Cls);
2661 ClsExprs.clear();
2662 ClsExprs.push_back(ArgExpr);
2663 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2664 &ClsExprs[0], ClsExprs.size(),
2665 StartLoc, EndLoc);
2666
2667 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2668 // To turn off a warning, type-cast to 'id'
2669 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2670 NoTypeInfoCStyleCastExpr(Context,
2671 Context->getObjCIdType(),
2672 CK_BitCast, Cls));
2673 // struct objc_super
2674 QualType superType = getSuperStructType();
2675 Expr *SuperRep;
2676
2677 if (LangOpts.MicrosoftExt) {
2678 SynthSuperContructorFunctionDecl();
2679 // Simulate a contructor call...
2680 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002681 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002682 SourceLocation());
2683 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2684 InitExprs.size(),
2685 superType, VK_LValue,
2686 SourceLocation());
2687 // The code for super is a little tricky to prevent collision with
2688 // the structure definition in the header. The rewriter has it's own
2689 // internal definition (__rw_objc_super) that is uses. This is why
2690 // we need the cast below. For example:
2691 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2692 //
2693 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2694 Context->getPointerType(SuperRep->getType()),
2695 VK_RValue, OK_Ordinary,
2696 SourceLocation());
2697 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2698 Context->getPointerType(superType),
2699 CK_BitCast, SuperRep);
2700 } else {
2701 // (struct objc_super) { <exprs from above> }
2702 InitListExpr *ILE =
2703 new (Context) InitListExpr(*Context, SourceLocation(),
2704 &InitExprs[0], InitExprs.size(),
2705 SourceLocation());
2706 TypeSourceInfo *superTInfo
2707 = Context->getTrivialTypeSourceInfo(superType);
2708 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2709 superType, VK_LValue,
2710 ILE, false);
2711 // struct objc_super *
2712 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2713 Context->getPointerType(SuperRep->getType()),
2714 VK_RValue, OK_Ordinary,
2715 SourceLocation());
2716 }
2717 MsgExprs.push_back(SuperRep);
2718 break;
2719 }
2720
2721 case ObjCMessageExpr::Class: {
2722 SmallVector<Expr*, 8> ClsExprs;
2723 QualType argType = Context->getPointerType(Context->CharTy);
2724 ObjCInterfaceDecl *Class
2725 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2726 IdentifierInfo *clsName = Class->getIdentifier();
2727 ClsExprs.push_back(StringLiteral::Create(*Context,
2728 clsName->getName(),
2729 StringLiteral::Ascii, false,
2730 argType, SourceLocation()));
2731 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2732 &ClsExprs[0],
2733 ClsExprs.size(),
2734 StartLoc, EndLoc);
2735 MsgExprs.push_back(Cls);
2736 break;
2737 }
2738
2739 case ObjCMessageExpr::SuperInstance:{
2740 MsgSendFlavor = MsgSendSuperFunctionDecl;
2741 if (MsgSendStretFlavor)
2742 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2743 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2744 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2745 SmallVector<Expr*, 4> InitExprs;
2746
2747 InitExprs.push_back(
2748 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2749 CK_BitCast,
2750 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002751 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002752 Context->getObjCIdType(),
2753 VK_RValue, SourceLocation()))
2754 ); // set the 'receiver'.
2755
2756 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2757 SmallVector<Expr*, 8> ClsExprs;
2758 QualType argType = Context->getPointerType(Context->CharTy);
2759 ClsExprs.push_back(StringLiteral::Create(*Context,
2760 ClassDecl->getIdentifier()->getName(),
2761 StringLiteral::Ascii, false, argType,
2762 SourceLocation()));
2763 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2764 &ClsExprs[0],
2765 ClsExprs.size(),
2766 StartLoc, EndLoc);
2767 // (Class)objc_getClass("CurrentClass")
2768 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2769 Context->getObjCClassType(),
2770 CK_BitCast, Cls);
2771 ClsExprs.clear();
2772 ClsExprs.push_back(ArgExpr);
2773 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2774 &ClsExprs[0], ClsExprs.size(),
2775 StartLoc, EndLoc);
2776
2777 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2778 // To turn off a warning, type-cast to 'id'
2779 InitExprs.push_back(
2780 // set 'super class', using class_getSuperclass().
2781 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2782 CK_BitCast, Cls));
2783 // struct objc_super
2784 QualType superType = getSuperStructType();
2785 Expr *SuperRep;
2786
2787 if (LangOpts.MicrosoftExt) {
2788 SynthSuperContructorFunctionDecl();
2789 // Simulate a contructor call...
2790 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002791 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002792 SourceLocation());
2793 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2794 InitExprs.size(),
2795 superType, VK_LValue, SourceLocation());
2796 // The code for super is a little tricky to prevent collision with
2797 // the structure definition in the header. The rewriter has it's own
2798 // internal definition (__rw_objc_super) that is uses. This is why
2799 // we need the cast below. For example:
2800 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2801 //
2802 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2803 Context->getPointerType(SuperRep->getType()),
2804 VK_RValue, OK_Ordinary,
2805 SourceLocation());
2806 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2807 Context->getPointerType(superType),
2808 CK_BitCast, SuperRep);
2809 } else {
2810 // (struct objc_super) { <exprs from above> }
2811 InitListExpr *ILE =
2812 new (Context) InitListExpr(*Context, SourceLocation(),
2813 &InitExprs[0], InitExprs.size(),
2814 SourceLocation());
2815 TypeSourceInfo *superTInfo
2816 = Context->getTrivialTypeSourceInfo(superType);
2817 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2818 superType, VK_RValue, ILE,
2819 false);
2820 }
2821 MsgExprs.push_back(SuperRep);
2822 break;
2823 }
2824
2825 case ObjCMessageExpr::Instance: {
2826 // Remove all type-casts because it may contain objc-style types; e.g.
2827 // Foo<Proto> *.
2828 Expr *recExpr = Exp->getInstanceReceiver();
2829 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2830 recExpr = CE->getSubExpr();
2831 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2832 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2833 ? CK_BlockPointerToObjCPointerCast
2834 : CK_CPointerToObjCPointerCast;
2835
2836 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2837 CK, recExpr);
2838 MsgExprs.push_back(recExpr);
2839 break;
2840 }
2841 }
2842
2843 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2844 SmallVector<Expr*, 8> SelExprs;
2845 QualType argType = Context->getPointerType(Context->CharTy);
2846 SelExprs.push_back(StringLiteral::Create(*Context,
2847 Exp->getSelector().getAsString(),
2848 StringLiteral::Ascii, false,
2849 argType, SourceLocation()));
2850 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2851 &SelExprs[0], SelExprs.size(),
2852 StartLoc,
2853 EndLoc);
2854 MsgExprs.push_back(SelExp);
2855
2856 // Now push any user supplied arguments.
2857 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2858 Expr *userExpr = Exp->getArg(i);
2859 // Make all implicit casts explicit...ICE comes in handy:-)
2860 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2861 // Reuse the ICE type, it is exactly what the doctor ordered.
2862 QualType type = ICE->getType();
2863 if (needToScanForQualifiers(type))
2864 type = Context->getObjCIdType();
2865 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2866 (void)convertBlockPointerToFunctionPointer(type);
2867 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2868 CastKind CK;
2869 if (SubExpr->getType()->isIntegralType(*Context) &&
2870 type->isBooleanType()) {
2871 CK = CK_IntegralToBoolean;
2872 } else if (type->isObjCObjectPointerType()) {
2873 if (SubExpr->getType()->isBlockPointerType()) {
2874 CK = CK_BlockPointerToObjCPointerCast;
2875 } else if (SubExpr->getType()->isPointerType()) {
2876 CK = CK_CPointerToObjCPointerCast;
2877 } else {
2878 CK = CK_BitCast;
2879 }
2880 } else {
2881 CK = CK_BitCast;
2882 }
2883
2884 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2885 }
2886 // Make id<P...> cast into an 'id' cast.
2887 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2888 if (CE->getType()->isObjCQualifiedIdType()) {
2889 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2890 userExpr = CE->getSubExpr();
2891 CastKind CK;
2892 if (userExpr->getType()->isIntegralType(*Context)) {
2893 CK = CK_IntegralToPointer;
2894 } else if (userExpr->getType()->isBlockPointerType()) {
2895 CK = CK_BlockPointerToObjCPointerCast;
2896 } else if (userExpr->getType()->isPointerType()) {
2897 CK = CK_CPointerToObjCPointerCast;
2898 } else {
2899 CK = CK_BitCast;
2900 }
2901 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2902 CK, userExpr);
2903 }
2904 }
2905 MsgExprs.push_back(userExpr);
2906 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2907 // out the argument in the original expression (since we aren't deleting
2908 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2909 //Exp->setArg(i, 0);
2910 }
2911 // Generate the funky cast.
2912 CastExpr *cast;
2913 SmallVector<QualType, 8> ArgTypes;
2914 QualType returnType;
2915
2916 // Push 'id' and 'SEL', the 2 implicit arguments.
2917 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2918 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2919 else
2920 ArgTypes.push_back(Context->getObjCIdType());
2921 ArgTypes.push_back(Context->getObjCSelType());
2922 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2923 // Push any user argument types.
2924 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2925 E = OMD->param_end(); PI != E; ++PI) {
2926 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2927 ? Context->getObjCIdType()
2928 : (*PI)->getType();
2929 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2930 (void)convertBlockPointerToFunctionPointer(t);
2931 ArgTypes.push_back(t);
2932 }
2933 returnType = Exp->getType();
2934 convertToUnqualifiedObjCType(returnType);
2935 (void)convertBlockPointerToFunctionPointer(returnType);
2936 } else {
2937 returnType = Context->getObjCIdType();
2938 }
2939 // Get the type, we will need to reference it in a couple spots.
2940 QualType msgSendType = MsgSendFlavor->getType();
2941
2942 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002943 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002944 VK_LValue, SourceLocation());
2945
2946 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2947 // If we don't do this cast, we get the following bizarre warning/note:
2948 // xx.m:13: warning: function called through a non-compatible type
2949 // xx.m:13: note: if this code is reached, the program will abort
2950 cast = NoTypeInfoCStyleCastExpr(Context,
2951 Context->getPointerType(Context->VoidTy),
2952 CK_BitCast, DRE);
2953
2954 // Now do the "normal" pointer to function cast.
2955 QualType castType =
2956 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2957 // If we don't have a method decl, force a variadic cast.
2958 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2959 castType = Context->getPointerType(castType);
2960 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2961 cast);
2962
2963 // Don't forget the parens to enforce the proper binding.
2964 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2965
2966 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2967 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2968 MsgExprs.size(),
2969 FT->getResultType(), VK_RValue,
2970 EndLoc);
2971 Stmt *ReplacingStmt = CE;
2972 if (MsgSendStretFlavor) {
2973 // We have the method which returns a struct/union. Must also generate
2974 // call to objc_msgSend_stret and hang both varieties on a conditional
2975 // expression which dictate which one to envoke depending on size of
2976 // method's return type.
2977
2978 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002979 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2980 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002981 VK_LValue, SourceLocation());
2982 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2983 cast = NoTypeInfoCStyleCastExpr(Context,
2984 Context->getPointerType(Context->VoidTy),
2985 CK_BitCast, STDRE);
2986 // Now do the "normal" pointer to function cast.
2987 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2988 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2989 castType = Context->getPointerType(castType);
2990 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2991 cast);
2992
2993 // Don't forget the parens to enforce the proper binding.
2994 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2995
2996 FT = msgSendType->getAs<FunctionType>();
2997 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2998 MsgExprs.size(),
2999 FT->getResultType(), VK_RValue,
3000 SourceLocation());
3001
3002 // Build sizeof(returnType)
3003 UnaryExprOrTypeTraitExpr *sizeofExpr =
3004 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3005 Context->getTrivialTypeSourceInfo(returnType),
3006 Context->getSizeType(), SourceLocation(),
3007 SourceLocation());
3008 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3009 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3010 // For X86 it is more complicated and some kind of target specific routine
3011 // is needed to decide what to do.
3012 unsigned IntSize =
3013 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3014 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3015 llvm::APInt(IntSize, 8),
3016 Context->IntTy,
3017 SourceLocation());
3018 BinaryOperator *lessThanExpr =
3019 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3020 VK_RValue, OK_Ordinary, SourceLocation());
3021 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3022 ConditionalOperator *CondExpr =
3023 new (Context) ConditionalOperator(lessThanExpr,
3024 SourceLocation(), CE,
3025 SourceLocation(), STCE,
3026 returnType, VK_RValue, OK_Ordinary);
3027 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3028 CondExpr);
3029 }
3030 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3031 return ReplacingStmt;
3032}
3033
3034Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3035 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3036 Exp->getLocEnd());
3037
3038 // Now do the actual rewrite.
3039 ReplaceStmt(Exp, ReplacingStmt);
3040
3041 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3042 return ReplacingStmt;
3043}
3044
3045// typedef struct objc_object Protocol;
3046QualType RewriteModernObjC::getProtocolType() {
3047 if (!ProtocolTypeDecl) {
3048 TypeSourceInfo *TInfo
3049 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3050 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3051 SourceLocation(), SourceLocation(),
3052 &Context->Idents.get("Protocol"),
3053 TInfo);
3054 }
3055 return Context->getTypeDeclType(ProtocolTypeDecl);
3056}
3057
3058/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3059/// a synthesized/forward data reference (to the protocol's metadata).
3060/// The forward references (and metadata) are generated in
3061/// RewriteModernObjC::HandleTranslationUnit().
3062Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003063 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3064 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003065 IdentifierInfo *ID = &Context->Idents.get(Name);
3066 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3067 SourceLocation(), ID, getProtocolType(), 0,
3068 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003069 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3070 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003071 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3072 Context->getPointerType(DRE->getType()),
3073 VK_RValue, OK_Ordinary, SourceLocation());
3074 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3075 CK_BitCast,
3076 DerefExpr);
3077 ReplaceStmt(Exp, castExpr);
3078 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3079 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3080 return castExpr;
3081
3082}
3083
3084bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3085 const char *endBuf) {
3086 while (startBuf < endBuf) {
3087 if (*startBuf == '#') {
3088 // Skip whitespace.
3089 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3090 ;
3091 if (!strncmp(startBuf, "if", strlen("if")) ||
3092 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3093 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3094 !strncmp(startBuf, "define", strlen("define")) ||
3095 !strncmp(startBuf, "undef", strlen("undef")) ||
3096 !strncmp(startBuf, "else", strlen("else")) ||
3097 !strncmp(startBuf, "elif", strlen("elif")) ||
3098 !strncmp(startBuf, "endif", strlen("endif")) ||
3099 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3100 !strncmp(startBuf, "include", strlen("include")) ||
3101 !strncmp(startBuf, "import", strlen("import")) ||
3102 !strncmp(startBuf, "include_next", strlen("include_next")))
3103 return true;
3104 }
3105 startBuf++;
3106 }
3107 return false;
3108}
3109
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003110/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003111/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003112bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3113 std::string &Result) {
3114 if (Type->isArrayType()) {
3115 QualType ElemTy = Context->getBaseElementType(Type);
3116 return RewriteObjCFieldDeclType(ElemTy, Result);
3117 }
3118 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003119 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3120 if (RD->isCompleteDefinition()) {
3121 if (RD->isStruct())
3122 Result += "\n\tstruct ";
3123 else if (RD->isUnion())
3124 Result += "\n\tunion ";
3125 else
3126 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003127
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003128 Result += RD->getName();
3129 if (TagsDefinedInIvarDecls.count(RD)) {
3130 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003131 Result += " ";
3132 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003133 }
3134 TagsDefinedInIvarDecls.insert(RD);
3135 Result += " {\n";
3136 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003137 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003138 FieldDecl *FD = *i;
3139 RewriteObjCFieldDecl(FD, Result);
3140 }
3141 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003142 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003143 }
3144 }
3145 else if (Type->isEnumeralType()) {
3146 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3147 if (ED->isCompleteDefinition()) {
3148 Result += "\n\tenum ";
3149 Result += ED->getName();
3150 if (TagsDefinedInIvarDecls.count(ED)) {
3151 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003152 Result += " ";
3153 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003154 }
3155 TagsDefinedInIvarDecls.insert(ED);
3156
3157 Result += " {\n";
3158 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3159 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3160 Result += "\t"; Result += EC->getName(); Result += " = ";
3161 llvm::APSInt Val = EC->getInitVal();
3162 Result += Val.toString(10);
3163 Result += ",\n";
3164 }
3165 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003166 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003167 }
3168 }
3169
3170 Result += "\t";
3171 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003172 return false;
3173}
3174
3175
3176/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3177/// It handles elaborated types, as well as enum types in the process.
3178void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3179 std::string &Result) {
3180 QualType Type = fieldDecl->getType();
3181 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003182
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003183 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3184 if (!EleboratedType)
3185 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003186 Result += Name;
3187 if (fieldDecl->isBitField()) {
3188 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3189 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003190 else if (EleboratedType && Type->isArrayType()) {
3191 CanQualType CType = Context->getCanonicalType(Type);
3192 while (isa<ArrayType>(CType)) {
3193 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3194 Result += "[";
3195 llvm::APInt Dim = CAT->getSize();
3196 Result += utostr(Dim.getZExtValue());
3197 Result += "]";
3198 }
3199 CType = CType->getAs<ArrayType>()->getElementType();
3200 }
3201 }
3202
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003203 Result += ";\n";
3204}
3205
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003206/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3207/// an objective-c class with ivars.
3208void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3209 std::string &Result) {
3210 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3211 assert(CDecl->getName() != "" &&
3212 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003213 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003214 SmallVector<ObjCIvarDecl *, 8> IVars;
3215 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003216 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003217 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003218
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003219 SourceLocation LocStart = CDecl->getLocStart();
3220 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003221
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003222 const char *startBuf = SM->getCharacterData(LocStart);
3223 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003224
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003225 // If no ivars and no root or if its root, directly or indirectly,
3226 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003227 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003228 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3229 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3230 ReplaceText(LocStart, endBuf-startBuf, Result);
3231 return;
3232 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003233
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003234 Result += "\nstruct ";
3235 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003236 Result += "_IMPL {\n";
3237
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003238 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003239 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3240 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3241 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003242 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003243 TagsDefinedInIvarDecls.clear();
3244 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3245 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003246
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003247 Result += "};\n";
3248 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3249 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003250 // Mark this struct as having been generated.
3251 if (!ObjCSynthesizedStructs.insert(CDecl))
3252 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003253}
3254
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003255/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3256/// have been referenced in an ivar access expression.
3257void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3258 std::string &Result) {
3259 // write out ivar offset symbols which have been referenced in an ivar
3260 // access expression.
3261 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3262 if (Ivars.empty())
3263 return;
3264 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3265 e = Ivars.end(); i != e; i++) {
3266 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003267 Result += "\n";
3268 if (LangOpts.MicrosoftExt)
3269 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3270 if (LangOpts.MicrosoftExt &&
3271 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3272 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3273 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3274 if (CDecl->getImplementation())
3275 Result += "__declspec(dllexport) ";
3276 }
3277 Result += "extern unsigned long OBJC_IVAR_$_";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003278 Result += CDecl->getName(); Result += "_";
3279 Result += IvarDecl->getName(); Result += ";";
3280 }
3281}
3282
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003283//===----------------------------------------------------------------------===//
3284// Meta Data Emission
3285//===----------------------------------------------------------------------===//
3286
3287
3288/// RewriteImplementations - This routine rewrites all method implementations
3289/// and emits meta-data.
3290
3291void RewriteModernObjC::RewriteImplementations() {
3292 int ClsDefCount = ClassImplementation.size();
3293 int CatDefCount = CategoryImplementation.size();
3294
3295 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003296 for (int i = 0; i < ClsDefCount; i++) {
3297 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3298 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3299 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003300 assert(false &&
3301 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003302 RewriteImplementationDecl(OIMP);
3303 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003304
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003305 for (int i = 0; i < CatDefCount; i++) {
3306 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3307 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3308 if (CDecl->isImplicitInterfaceDecl())
3309 assert(false &&
3310 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003311 RewriteImplementationDecl(CIMP);
3312 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003313}
3314
3315void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3316 const std::string &Name,
3317 ValueDecl *VD, bool def) {
3318 assert(BlockByRefDeclNo.count(VD) &&
3319 "RewriteByRefString: ByRef decl missing");
3320 if (def)
3321 ResultStr += "struct ";
3322 ResultStr += "__Block_byref_" + Name +
3323 "_" + utostr(BlockByRefDeclNo[VD]) ;
3324}
3325
3326static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3327 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3328 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3329 return false;
3330}
3331
3332std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3333 StringRef funcName,
3334 std::string Tag) {
3335 const FunctionType *AFT = CE->getFunctionType();
3336 QualType RT = AFT->getResultType();
3337 std::string StructRef = "struct " + Tag;
3338 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3339 funcName.str() + "_" + "block_func_" + utostr(i);
3340
3341 BlockDecl *BD = CE->getBlockDecl();
3342
3343 if (isa<FunctionNoProtoType>(AFT)) {
3344 // No user-supplied arguments. Still need to pass in a pointer to the
3345 // block (to reference imported block decl refs).
3346 S += "(" + StructRef + " *__cself)";
3347 } else if (BD->param_empty()) {
3348 S += "(" + StructRef + " *__cself)";
3349 } else {
3350 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3351 assert(FT && "SynthesizeBlockFunc: No function proto");
3352 S += '(';
3353 // first add the implicit argument.
3354 S += StructRef + " *__cself, ";
3355 std::string ParamStr;
3356 for (BlockDecl::param_iterator AI = BD->param_begin(),
3357 E = BD->param_end(); AI != E; ++AI) {
3358 if (AI != BD->param_begin()) S += ", ";
3359 ParamStr = (*AI)->getNameAsString();
3360 QualType QT = (*AI)->getType();
3361 if (convertBlockPointerToFunctionPointer(QT))
3362 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3363 else
3364 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3365 S += ParamStr;
3366 }
3367 if (FT->isVariadic()) {
3368 if (!BD->param_empty()) S += ", ";
3369 S += "...";
3370 }
3371 S += ')';
3372 }
3373 S += " {\n";
3374
3375 // Create local declarations to avoid rewriting all closure decl ref exprs.
3376 // First, emit a declaration for all "by ref" decls.
3377 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3378 E = BlockByRefDecls.end(); I != E; ++I) {
3379 S += " ";
3380 std::string Name = (*I)->getNameAsString();
3381 std::string TypeString;
3382 RewriteByRefString(TypeString, Name, (*I));
3383 TypeString += " *";
3384 Name = TypeString + Name;
3385 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3386 }
3387 // Next, emit a declaration for all "by copy" declarations.
3388 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3389 E = BlockByCopyDecls.end(); I != E; ++I) {
3390 S += " ";
3391 // Handle nested closure invocation. For example:
3392 //
3393 // void (^myImportedClosure)(void);
3394 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3395 //
3396 // void (^anotherClosure)(void);
3397 // anotherClosure = ^(void) {
3398 // myImportedClosure(); // import and invoke the closure
3399 // };
3400 //
3401 if (isTopLevelBlockPointerType((*I)->getType())) {
3402 RewriteBlockPointerTypeVariable(S, (*I));
3403 S += " = (";
3404 RewriteBlockPointerType(S, (*I)->getType());
3405 S += ")";
3406 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3407 }
3408 else {
3409 std::string Name = (*I)->getNameAsString();
3410 QualType QT = (*I)->getType();
3411 if (HasLocalVariableExternalStorage(*I))
3412 QT = Context->getPointerType(QT);
3413 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3414 S += Name + " = __cself->" +
3415 (*I)->getNameAsString() + "; // bound by copy\n";
3416 }
3417 }
3418 std::string RewrittenStr = RewrittenBlockExprs[CE];
3419 const char *cstr = RewrittenStr.c_str();
3420 while (*cstr++ != '{') ;
3421 S += cstr;
3422 S += "\n";
3423 return S;
3424}
3425
3426std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3427 StringRef funcName,
3428 std::string Tag) {
3429 std::string StructRef = "struct " + Tag;
3430 std::string S = "static void __";
3431
3432 S += funcName;
3433 S += "_block_copy_" + utostr(i);
3434 S += "(" + StructRef;
3435 S += "*dst, " + StructRef;
3436 S += "*src) {";
3437 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3438 E = ImportedBlockDecls.end(); I != E; ++I) {
3439 ValueDecl *VD = (*I);
3440 S += "_Block_object_assign((void*)&dst->";
3441 S += (*I)->getNameAsString();
3442 S += ", (void*)src->";
3443 S += (*I)->getNameAsString();
3444 if (BlockByRefDeclsPtrSet.count((*I)))
3445 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3446 else if (VD->getType()->isBlockPointerType())
3447 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3448 else
3449 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3450 }
3451 S += "}\n";
3452
3453 S += "\nstatic void __";
3454 S += funcName;
3455 S += "_block_dispose_" + utostr(i);
3456 S += "(" + StructRef;
3457 S += "*src) {";
3458 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3459 E = ImportedBlockDecls.end(); I != E; ++I) {
3460 ValueDecl *VD = (*I);
3461 S += "_Block_object_dispose((void*)src->";
3462 S += (*I)->getNameAsString();
3463 if (BlockByRefDeclsPtrSet.count((*I)))
3464 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3465 else if (VD->getType()->isBlockPointerType())
3466 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3467 else
3468 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3469 }
3470 S += "}\n";
3471 return S;
3472}
3473
3474std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3475 std::string Desc) {
3476 std::string S = "\nstruct " + Tag;
3477 std::string Constructor = " " + Tag;
3478
3479 S += " {\n struct __block_impl impl;\n";
3480 S += " struct " + Desc;
3481 S += "* Desc;\n";
3482
3483 Constructor += "(void *fp, "; // Invoke function pointer.
3484 Constructor += "struct " + Desc; // Descriptor pointer.
3485 Constructor += " *desc";
3486
3487 if (BlockDeclRefs.size()) {
3488 // Output all "by copy" declarations.
3489 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3490 E = BlockByCopyDecls.end(); I != E; ++I) {
3491 S += " ";
3492 std::string FieldName = (*I)->getNameAsString();
3493 std::string ArgName = "_" + FieldName;
3494 // Handle nested closure invocation. For example:
3495 //
3496 // void (^myImportedBlock)(void);
3497 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3498 //
3499 // void (^anotherBlock)(void);
3500 // anotherBlock = ^(void) {
3501 // myImportedBlock(); // import and invoke the closure
3502 // };
3503 //
3504 if (isTopLevelBlockPointerType((*I)->getType())) {
3505 S += "struct __block_impl *";
3506 Constructor += ", void *" + ArgName;
3507 } else {
3508 QualType QT = (*I)->getType();
3509 if (HasLocalVariableExternalStorage(*I))
3510 QT = Context->getPointerType(QT);
3511 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3512 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3513 Constructor += ", " + ArgName;
3514 }
3515 S += FieldName + ";\n";
3516 }
3517 // Output all "by ref" declarations.
3518 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3519 E = BlockByRefDecls.end(); I != E; ++I) {
3520 S += " ";
3521 std::string FieldName = (*I)->getNameAsString();
3522 std::string ArgName = "_" + FieldName;
3523 {
3524 std::string TypeString;
3525 RewriteByRefString(TypeString, FieldName, (*I));
3526 TypeString += " *";
3527 FieldName = TypeString + FieldName;
3528 ArgName = TypeString + ArgName;
3529 Constructor += ", " + ArgName;
3530 }
3531 S += FieldName + "; // by ref\n";
3532 }
3533 // Finish writing the constructor.
3534 Constructor += ", int flags=0)";
3535 // Initialize all "by copy" arguments.
3536 bool firsTime = true;
3537 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3538 E = BlockByCopyDecls.end(); I != E; ++I) {
3539 std::string Name = (*I)->getNameAsString();
3540 if (firsTime) {
3541 Constructor += " : ";
3542 firsTime = false;
3543 }
3544 else
3545 Constructor += ", ";
3546 if (isTopLevelBlockPointerType((*I)->getType()))
3547 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3548 else
3549 Constructor += Name + "(_" + Name + ")";
3550 }
3551 // Initialize all "by ref" arguments.
3552 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3553 E = BlockByRefDecls.end(); I != E; ++I) {
3554 std::string Name = (*I)->getNameAsString();
3555 if (firsTime) {
3556 Constructor += " : ";
3557 firsTime = false;
3558 }
3559 else
3560 Constructor += ", ";
3561 Constructor += Name + "(_" + Name + "->__forwarding)";
3562 }
3563
3564 Constructor += " {\n";
3565 if (GlobalVarDecl)
3566 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3567 else
3568 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3569 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3570
3571 Constructor += " Desc = desc;\n";
3572 } else {
3573 // Finish writing the constructor.
3574 Constructor += ", int flags=0) {\n";
3575 if (GlobalVarDecl)
3576 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3577 else
3578 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3579 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3580 Constructor += " Desc = desc;\n";
3581 }
3582 Constructor += " ";
3583 Constructor += "}\n";
3584 S += Constructor;
3585 S += "};\n";
3586 return S;
3587}
3588
3589std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3590 std::string ImplTag, int i,
3591 StringRef FunName,
3592 unsigned hasCopy) {
3593 std::string S = "\nstatic struct " + DescTag;
3594
3595 S += " {\n unsigned long reserved;\n";
3596 S += " unsigned long Block_size;\n";
3597 if (hasCopy) {
3598 S += " void (*copy)(struct ";
3599 S += ImplTag; S += "*, struct ";
3600 S += ImplTag; S += "*);\n";
3601
3602 S += " void (*dispose)(struct ";
3603 S += ImplTag; S += "*);\n";
3604 }
3605 S += "} ";
3606
3607 S += DescTag + "_DATA = { 0, sizeof(struct ";
3608 S += ImplTag + ")";
3609 if (hasCopy) {
3610 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3611 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3612 }
3613 S += "};\n";
3614 return S;
3615}
3616
3617void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3618 StringRef FunName) {
3619 // Insert declaration for the function in which block literal is used.
3620 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3621 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3622 bool RewriteSC = (GlobalVarDecl &&
3623 !Blocks.empty() &&
3624 GlobalVarDecl->getStorageClass() == SC_Static &&
3625 GlobalVarDecl->getType().getCVRQualifiers());
3626 if (RewriteSC) {
3627 std::string SC(" void __");
3628 SC += GlobalVarDecl->getNameAsString();
3629 SC += "() {}";
3630 InsertText(FunLocStart, SC);
3631 }
3632
3633 // Insert closures that were part of the function.
3634 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3635 CollectBlockDeclRefInfo(Blocks[i]);
3636 // Need to copy-in the inner copied-in variables not actually used in this
3637 // block.
3638 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003639 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003640 ValueDecl *VD = Exp->getDecl();
3641 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003642 if (!VD->hasAttr<BlocksAttr>()) {
3643 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3644 BlockByCopyDeclsPtrSet.insert(VD);
3645 BlockByCopyDecls.push_back(VD);
3646 }
3647 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003648 }
John McCallf4b88a42012-03-10 09:33:50 +00003649
3650 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003651 BlockByRefDeclsPtrSet.insert(VD);
3652 BlockByRefDecls.push_back(VD);
3653 }
John McCallf4b88a42012-03-10 09:33:50 +00003654
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003655 // imported objects in the inner blocks not used in the outer
3656 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003657 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003658 VD->getType()->isBlockPointerType())
3659 ImportedBlockDecls.insert(VD);
3660 }
3661
3662 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3663 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3664
3665 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3666
3667 InsertText(FunLocStart, CI);
3668
3669 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3670
3671 InsertText(FunLocStart, CF);
3672
3673 if (ImportedBlockDecls.size()) {
3674 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3675 InsertText(FunLocStart, HF);
3676 }
3677 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3678 ImportedBlockDecls.size() > 0);
3679 InsertText(FunLocStart, BD);
3680
3681 BlockDeclRefs.clear();
3682 BlockByRefDecls.clear();
3683 BlockByRefDeclsPtrSet.clear();
3684 BlockByCopyDecls.clear();
3685 BlockByCopyDeclsPtrSet.clear();
3686 ImportedBlockDecls.clear();
3687 }
3688 if (RewriteSC) {
3689 // Must insert any 'const/volatile/static here. Since it has been
3690 // removed as result of rewriting of block literals.
3691 std::string SC;
3692 if (GlobalVarDecl->getStorageClass() == SC_Static)
3693 SC = "static ";
3694 if (GlobalVarDecl->getType().isConstQualified())
3695 SC += "const ";
3696 if (GlobalVarDecl->getType().isVolatileQualified())
3697 SC += "volatile ";
3698 if (GlobalVarDecl->getType().isRestrictQualified())
3699 SC += "restrict ";
3700 InsertText(FunLocStart, SC);
3701 }
3702
3703 Blocks.clear();
3704 InnerDeclRefsCount.clear();
3705 InnerDeclRefs.clear();
3706 RewrittenBlockExprs.clear();
3707}
3708
3709void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3710 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3711 StringRef FuncName = FD->getName();
3712
3713 SynthesizeBlockLiterals(FunLocStart, FuncName);
3714}
3715
3716static void BuildUniqueMethodName(std::string &Name,
3717 ObjCMethodDecl *MD) {
3718 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3719 Name = IFace->getName();
3720 Name += "__" + MD->getSelector().getAsString();
3721 // Convert colons to underscores.
3722 std::string::size_type loc = 0;
3723 while ((loc = Name.find(":", loc)) != std::string::npos)
3724 Name.replace(loc, 1, "_");
3725}
3726
3727void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3728 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3729 //SourceLocation FunLocStart = MD->getLocStart();
3730 SourceLocation FunLocStart = MD->getLocStart();
3731 std::string FuncName;
3732 BuildUniqueMethodName(FuncName, MD);
3733 SynthesizeBlockLiterals(FunLocStart, FuncName);
3734}
3735
3736void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3737 for (Stmt::child_range CI = S->children(); CI; ++CI)
3738 if (*CI) {
3739 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3740 GetBlockDeclRefExprs(CBE->getBody());
3741 else
3742 GetBlockDeclRefExprs(*CI);
3743 }
3744 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003745 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3746 if (DRE->refersToEnclosingLocal() &&
3747 HasLocalVariableExternalStorage(DRE->getDecl())) {
3748 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003749 }
3750
3751 return;
3752}
3753
3754void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003755 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003756 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3757 for (Stmt::child_range CI = S->children(); CI; ++CI)
3758 if (*CI) {
3759 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3760 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3761 GetInnerBlockDeclRefExprs(CBE->getBody(),
3762 InnerBlockDeclRefs,
3763 InnerContexts);
3764 }
3765 else
3766 GetInnerBlockDeclRefExprs(*CI,
3767 InnerBlockDeclRefs,
3768 InnerContexts);
3769
3770 }
3771 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003772 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3773 if (DRE->refersToEnclosingLocal()) {
3774 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3775 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3776 InnerBlockDeclRefs.push_back(DRE);
3777 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3778 if (Var->isFunctionOrMethodVarDecl())
3779 ImportedLocalExternalDecls.insert(Var);
3780 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003781 }
3782
3783 return;
3784}
3785
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003786/// convertObjCTypeToCStyleType - This routine converts such objc types
3787/// as qualified objects, and blocks to their closest c/c++ types that
3788/// it can. It returns true if input type was modified.
3789bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3790 QualType oldT = T;
3791 convertBlockPointerToFunctionPointer(T);
3792 if (T->isFunctionPointerType()) {
3793 QualType PointeeTy;
3794 if (const PointerType* PT = T->getAs<PointerType>()) {
3795 PointeeTy = PT->getPointeeType();
3796 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3797 T = convertFunctionTypeOfBlocks(FT);
3798 T = Context->getPointerType(T);
3799 }
3800 }
3801 }
3802
3803 convertToUnqualifiedObjCType(T);
3804 return T != oldT;
3805}
3806
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003807/// convertFunctionTypeOfBlocks - This routine converts a function type
3808/// whose result type may be a block pointer or whose argument type(s)
3809/// might be block pointers to an equivalent function type replacing
3810/// all block pointers to function pointers.
3811QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3812 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3813 // FTP will be null for closures that don't take arguments.
3814 // Generate a funky cast.
3815 SmallVector<QualType, 8> ArgTypes;
3816 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003817 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003818
3819 if (FTP) {
3820 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3821 E = FTP->arg_type_end(); I && (I != E); ++I) {
3822 QualType t = *I;
3823 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003824 if (convertObjCTypeToCStyleType(t))
3825 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003826 ArgTypes.push_back(t);
3827 }
3828 }
3829 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003830 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003831 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3832 else FuncType = QualType(FT, 0);
3833 return FuncType;
3834}
3835
3836Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3837 // Navigate to relevant type information.
3838 const BlockPointerType *CPT = 0;
3839
3840 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3841 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003842 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3843 CPT = MExpr->getType()->getAs<BlockPointerType>();
3844 }
3845 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3846 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3847 }
3848 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3849 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3850 else if (const ConditionalOperator *CEXPR =
3851 dyn_cast<ConditionalOperator>(BlockExp)) {
3852 Expr *LHSExp = CEXPR->getLHS();
3853 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3854 Expr *RHSExp = CEXPR->getRHS();
3855 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3856 Expr *CONDExp = CEXPR->getCond();
3857 ConditionalOperator *CondExpr =
3858 new (Context) ConditionalOperator(CONDExp,
3859 SourceLocation(), cast<Expr>(LHSStmt),
3860 SourceLocation(), cast<Expr>(RHSStmt),
3861 Exp->getType(), VK_RValue, OK_Ordinary);
3862 return CondExpr;
3863 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3864 CPT = IRE->getType()->getAs<BlockPointerType>();
3865 } else if (const PseudoObjectExpr *POE
3866 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3867 CPT = POE->getType()->castAs<BlockPointerType>();
3868 } else {
3869 assert(1 && "RewriteBlockClass: Bad type");
3870 }
3871 assert(CPT && "RewriteBlockClass: Bad type");
3872 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3873 assert(FT && "RewriteBlockClass: Bad type");
3874 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3875 // FTP will be null for closures that don't take arguments.
3876
3877 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3878 SourceLocation(), SourceLocation(),
3879 &Context->Idents.get("__block_impl"));
3880 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3881
3882 // Generate a funky cast.
3883 SmallVector<QualType, 8> ArgTypes;
3884
3885 // Push the block argument type.
3886 ArgTypes.push_back(PtrBlock);
3887 if (FTP) {
3888 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3889 E = FTP->arg_type_end(); I && (I != E); ++I) {
3890 QualType t = *I;
3891 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3892 if (!convertBlockPointerToFunctionPointer(t))
3893 convertToUnqualifiedObjCType(t);
3894 ArgTypes.push_back(t);
3895 }
3896 }
3897 // Now do the pointer to function cast.
3898 QualType PtrToFuncCastType
3899 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3900
3901 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3902
3903 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3904 CK_BitCast,
3905 const_cast<Expr*>(BlockExp));
3906 // Don't forget the parens to enforce the proper binding.
3907 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3908 BlkCast);
3909 //PE->dump();
3910
3911 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3912 SourceLocation(),
3913 &Context->Idents.get("FuncPtr"),
3914 Context->VoidPtrTy, 0,
3915 /*BitWidth=*/0, /*Mutable=*/true,
3916 /*HasInit=*/false);
3917 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3918 FD->getType(), VK_LValue,
3919 OK_Ordinary);
3920
3921
3922 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3923 CK_BitCast, ME);
3924 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3925
3926 SmallVector<Expr*, 8> BlkExprs;
3927 // Add the implicit argument.
3928 BlkExprs.push_back(BlkCast);
3929 // Add the user arguments.
3930 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3931 E = Exp->arg_end(); I != E; ++I) {
3932 BlkExprs.push_back(*I);
3933 }
3934 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3935 BlkExprs.size(),
3936 Exp->getType(), VK_RValue,
3937 SourceLocation());
3938 return CE;
3939}
3940
3941// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003942// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003943// For example:
3944//
3945// int main() {
3946// __block Foo *f;
3947// __block int i;
3948//
3949// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003950// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003951// i = 77;
3952// };
3953//}
John McCallf4b88a42012-03-10 09:33:50 +00003954Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003955 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3956 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003957 ValueDecl *VD = DeclRefExp->getDecl();
3958 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003959
3960 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3961 SourceLocation(),
3962 &Context->Idents.get("__forwarding"),
3963 Context->VoidPtrTy, 0,
3964 /*BitWidth=*/0, /*Mutable=*/true,
3965 /*HasInit=*/false);
3966 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3967 FD, SourceLocation(),
3968 FD->getType(), VK_LValue,
3969 OK_Ordinary);
3970
3971 StringRef Name = VD->getName();
3972 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3973 &Context->Idents.get(Name),
3974 Context->VoidPtrTy, 0,
3975 /*BitWidth=*/0, /*Mutable=*/true,
3976 /*HasInit=*/false);
3977 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3978 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3979
3980
3981
3982 // Need parens to enforce precedence.
3983 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3984 DeclRefExp->getExprLoc(),
3985 ME);
3986 ReplaceStmt(DeclRefExp, PE);
3987 return PE;
3988}
3989
3990// Rewrites the imported local variable V with external storage
3991// (static, extern, etc.) as *V
3992//
3993Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3994 ValueDecl *VD = DRE->getDecl();
3995 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3996 if (!ImportedLocalExternalDecls.count(Var))
3997 return DRE;
3998 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3999 VK_LValue, OK_Ordinary,
4000 DRE->getLocation());
4001 // Need parens to enforce precedence.
4002 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4003 Exp);
4004 ReplaceStmt(DRE, PE);
4005 return PE;
4006}
4007
4008void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4009 SourceLocation LocStart = CE->getLParenLoc();
4010 SourceLocation LocEnd = CE->getRParenLoc();
4011
4012 // Need to avoid trying to rewrite synthesized casts.
4013 if (LocStart.isInvalid())
4014 return;
4015 // Need to avoid trying to rewrite casts contained in macros.
4016 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4017 return;
4018
4019 const char *startBuf = SM->getCharacterData(LocStart);
4020 const char *endBuf = SM->getCharacterData(LocEnd);
4021 QualType QT = CE->getType();
4022 const Type* TypePtr = QT->getAs<Type>();
4023 if (isa<TypeOfExprType>(TypePtr)) {
4024 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4025 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4026 std::string TypeAsString = "(";
4027 RewriteBlockPointerType(TypeAsString, QT);
4028 TypeAsString += ")";
4029 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4030 return;
4031 }
4032 // advance the location to startArgList.
4033 const char *argPtr = startBuf;
4034
4035 while (*argPtr++ && (argPtr < endBuf)) {
4036 switch (*argPtr) {
4037 case '^':
4038 // Replace the '^' with '*'.
4039 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4040 ReplaceText(LocStart, 1, "*");
4041 break;
4042 }
4043 }
4044 return;
4045}
4046
4047void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4048 SourceLocation DeclLoc = FD->getLocation();
4049 unsigned parenCount = 0;
4050
4051 // We have 1 or more arguments that have closure pointers.
4052 const char *startBuf = SM->getCharacterData(DeclLoc);
4053 const char *startArgList = strchr(startBuf, '(');
4054
4055 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4056
4057 parenCount++;
4058 // advance the location to startArgList.
4059 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4060 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4061
4062 const char *argPtr = startArgList;
4063
4064 while (*argPtr++ && parenCount) {
4065 switch (*argPtr) {
4066 case '^':
4067 // Replace the '^' with '*'.
4068 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4069 ReplaceText(DeclLoc, 1, "*");
4070 break;
4071 case '(':
4072 parenCount++;
4073 break;
4074 case ')':
4075 parenCount--;
4076 break;
4077 }
4078 }
4079 return;
4080}
4081
4082bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4083 const FunctionProtoType *FTP;
4084 const PointerType *PT = QT->getAs<PointerType>();
4085 if (PT) {
4086 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4087 } else {
4088 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4089 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4090 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4091 }
4092 if (FTP) {
4093 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4094 E = FTP->arg_type_end(); I != E; ++I)
4095 if (isTopLevelBlockPointerType(*I))
4096 return true;
4097 }
4098 return false;
4099}
4100
4101bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4102 const FunctionProtoType *FTP;
4103 const PointerType *PT = QT->getAs<PointerType>();
4104 if (PT) {
4105 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4106 } else {
4107 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4108 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4109 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4110 }
4111 if (FTP) {
4112 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4113 E = FTP->arg_type_end(); I != E; ++I) {
4114 if ((*I)->isObjCQualifiedIdType())
4115 return true;
4116 if ((*I)->isObjCObjectPointerType() &&
4117 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4118 return true;
4119 }
4120
4121 }
4122 return false;
4123}
4124
4125void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4126 const char *&RParen) {
4127 const char *argPtr = strchr(Name, '(');
4128 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4129
4130 LParen = argPtr; // output the start.
4131 argPtr++; // skip past the left paren.
4132 unsigned parenCount = 1;
4133
4134 while (*argPtr && parenCount) {
4135 switch (*argPtr) {
4136 case '(': parenCount++; break;
4137 case ')': parenCount--; break;
4138 default: break;
4139 }
4140 if (parenCount) argPtr++;
4141 }
4142 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4143 RParen = argPtr; // output the end
4144}
4145
4146void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4147 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4148 RewriteBlockPointerFunctionArgs(FD);
4149 return;
4150 }
4151 // Handle Variables and Typedefs.
4152 SourceLocation DeclLoc = ND->getLocation();
4153 QualType DeclT;
4154 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4155 DeclT = VD->getType();
4156 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4157 DeclT = TDD->getUnderlyingType();
4158 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4159 DeclT = FD->getType();
4160 else
4161 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4162
4163 const char *startBuf = SM->getCharacterData(DeclLoc);
4164 const char *endBuf = startBuf;
4165 // scan backward (from the decl location) for the end of the previous decl.
4166 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4167 startBuf--;
4168 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4169 std::string buf;
4170 unsigned OrigLength=0;
4171 // *startBuf != '^' if we are dealing with a pointer to function that
4172 // may take block argument types (which will be handled below).
4173 if (*startBuf == '^') {
4174 // Replace the '^' with '*', computing a negative offset.
4175 buf = '*';
4176 startBuf++;
4177 OrigLength++;
4178 }
4179 while (*startBuf != ')') {
4180 buf += *startBuf;
4181 startBuf++;
4182 OrigLength++;
4183 }
4184 buf += ')';
4185 OrigLength++;
4186
4187 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4188 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4189 // Replace the '^' with '*' for arguments.
4190 // Replace id<P> with id/*<>*/
4191 DeclLoc = ND->getLocation();
4192 startBuf = SM->getCharacterData(DeclLoc);
4193 const char *argListBegin, *argListEnd;
4194 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4195 while (argListBegin < argListEnd) {
4196 if (*argListBegin == '^')
4197 buf += '*';
4198 else if (*argListBegin == '<') {
4199 buf += "/*";
4200 buf += *argListBegin++;
4201 OrigLength++;;
4202 while (*argListBegin != '>') {
4203 buf += *argListBegin++;
4204 OrigLength++;
4205 }
4206 buf += *argListBegin;
4207 buf += "*/";
4208 }
4209 else
4210 buf += *argListBegin;
4211 argListBegin++;
4212 OrigLength++;
4213 }
4214 buf += ')';
4215 OrigLength++;
4216 }
4217 ReplaceText(Start, OrigLength, buf);
4218
4219 return;
4220}
4221
4222
4223/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4224/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4225/// struct Block_byref_id_object *src) {
4226/// _Block_object_assign (&_dest->object, _src->object,
4227/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4228/// [|BLOCK_FIELD_IS_WEAK]) // object
4229/// _Block_object_assign(&_dest->object, _src->object,
4230/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4231/// [|BLOCK_FIELD_IS_WEAK]) // block
4232/// }
4233/// And:
4234/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4235/// _Block_object_dispose(_src->object,
4236/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4237/// [|BLOCK_FIELD_IS_WEAK]) // object
4238/// _Block_object_dispose(_src->object,
4239/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4240/// [|BLOCK_FIELD_IS_WEAK]) // block
4241/// }
4242
4243std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4244 int flag) {
4245 std::string S;
4246 if (CopyDestroyCache.count(flag))
4247 return S;
4248 CopyDestroyCache.insert(flag);
4249 S = "static void __Block_byref_id_object_copy_";
4250 S += utostr(flag);
4251 S += "(void *dst, void *src) {\n";
4252
4253 // offset into the object pointer is computed as:
4254 // void * + void* + int + int + void* + void *
4255 unsigned IntSize =
4256 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4257 unsigned VoidPtrSize =
4258 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4259
4260 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4261 S += " _Block_object_assign((char*)dst + ";
4262 S += utostr(offset);
4263 S += ", *(void * *) ((char*)src + ";
4264 S += utostr(offset);
4265 S += "), ";
4266 S += utostr(flag);
4267 S += ");\n}\n";
4268
4269 S += "static void __Block_byref_id_object_dispose_";
4270 S += utostr(flag);
4271 S += "(void *src) {\n";
4272 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4273 S += utostr(offset);
4274 S += "), ";
4275 S += utostr(flag);
4276 S += ");\n}\n";
4277 return S;
4278}
4279
4280/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4281/// the declaration into:
4282/// struct __Block_byref_ND {
4283/// void *__isa; // NULL for everything except __weak pointers
4284/// struct __Block_byref_ND *__forwarding;
4285/// int32_t __flags;
4286/// int32_t __size;
4287/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4288/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4289/// typex ND;
4290/// };
4291///
4292/// It then replaces declaration of ND variable with:
4293/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4294/// __size=sizeof(struct __Block_byref_ND),
4295/// ND=initializer-if-any};
4296///
4297///
4298void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4299 // Insert declaration for the function in which block literal is
4300 // used.
4301 if (CurFunctionDeclToDeclareForBlock)
4302 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4303 int flag = 0;
4304 int isa = 0;
4305 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4306 if (DeclLoc.isInvalid())
4307 // If type location is missing, it is because of missing type (a warning).
4308 // Use variable's location which is good for this case.
4309 DeclLoc = ND->getLocation();
4310 const char *startBuf = SM->getCharacterData(DeclLoc);
4311 SourceLocation X = ND->getLocEnd();
4312 X = SM->getExpansionLoc(X);
4313 const char *endBuf = SM->getCharacterData(X);
4314 std::string Name(ND->getNameAsString());
4315 std::string ByrefType;
4316 RewriteByRefString(ByrefType, Name, ND, true);
4317 ByrefType += " {\n";
4318 ByrefType += " void *__isa;\n";
4319 RewriteByRefString(ByrefType, Name, ND);
4320 ByrefType += " *__forwarding;\n";
4321 ByrefType += " int __flags;\n";
4322 ByrefType += " int __size;\n";
4323 // Add void *__Block_byref_id_object_copy;
4324 // void *__Block_byref_id_object_dispose; if needed.
4325 QualType Ty = ND->getType();
4326 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4327 if (HasCopyAndDispose) {
4328 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4329 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4330 }
4331
4332 QualType T = Ty;
4333 (void)convertBlockPointerToFunctionPointer(T);
4334 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4335
4336 ByrefType += " " + Name + ";\n";
4337 ByrefType += "};\n";
4338 // Insert this type in global scope. It is needed by helper function.
4339 SourceLocation FunLocStart;
4340 if (CurFunctionDef)
4341 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4342 else {
4343 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4344 FunLocStart = CurMethodDef->getLocStart();
4345 }
4346 InsertText(FunLocStart, ByrefType);
4347 if (Ty.isObjCGCWeak()) {
4348 flag |= BLOCK_FIELD_IS_WEAK;
4349 isa = 1;
4350 }
4351
4352 if (HasCopyAndDispose) {
4353 flag = BLOCK_BYREF_CALLER;
4354 QualType Ty = ND->getType();
4355 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4356 if (Ty->isBlockPointerType())
4357 flag |= BLOCK_FIELD_IS_BLOCK;
4358 else
4359 flag |= BLOCK_FIELD_IS_OBJECT;
4360 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4361 if (!HF.empty())
4362 InsertText(FunLocStart, HF);
4363 }
4364
4365 // struct __Block_byref_ND ND =
4366 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4367 // initializer-if-any};
4368 bool hasInit = (ND->getInit() != 0);
4369 unsigned flags = 0;
4370 if (HasCopyAndDispose)
4371 flags |= BLOCK_HAS_COPY_DISPOSE;
4372 Name = ND->getNameAsString();
4373 ByrefType.clear();
4374 RewriteByRefString(ByrefType, Name, ND);
4375 std::string ForwardingCastType("(");
4376 ForwardingCastType += ByrefType + " *)";
4377 if (!hasInit) {
4378 ByrefType += " " + Name + " = {(void*)";
4379 ByrefType += utostr(isa);
4380 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4381 ByrefType += utostr(flags);
4382 ByrefType += ", ";
4383 ByrefType += "sizeof(";
4384 RewriteByRefString(ByrefType, Name, ND);
4385 ByrefType += ")";
4386 if (HasCopyAndDispose) {
4387 ByrefType += ", __Block_byref_id_object_copy_";
4388 ByrefType += utostr(flag);
4389 ByrefType += ", __Block_byref_id_object_dispose_";
4390 ByrefType += utostr(flag);
4391 }
4392 ByrefType += "};\n";
4393 unsigned nameSize = Name.size();
4394 // for block or function pointer declaration. Name is aleady
4395 // part of the declaration.
4396 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4397 nameSize = 1;
4398 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4399 }
4400 else {
4401 SourceLocation startLoc;
4402 Expr *E = ND->getInit();
4403 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4404 startLoc = ECE->getLParenLoc();
4405 else
4406 startLoc = E->getLocStart();
4407 startLoc = SM->getExpansionLoc(startLoc);
4408 endBuf = SM->getCharacterData(startLoc);
4409 ByrefType += " " + Name;
4410 ByrefType += " = {(void*)";
4411 ByrefType += utostr(isa);
4412 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4413 ByrefType += utostr(flags);
4414 ByrefType += ", ";
4415 ByrefType += "sizeof(";
4416 RewriteByRefString(ByrefType, Name, ND);
4417 ByrefType += "), ";
4418 if (HasCopyAndDispose) {
4419 ByrefType += "__Block_byref_id_object_copy_";
4420 ByrefType += utostr(flag);
4421 ByrefType += ", __Block_byref_id_object_dispose_";
4422 ByrefType += utostr(flag);
4423 ByrefType += ", ";
4424 }
4425 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4426
4427 // Complete the newly synthesized compound expression by inserting a right
4428 // curly brace before the end of the declaration.
4429 // FIXME: This approach avoids rewriting the initializer expression. It
4430 // also assumes there is only one declarator. For example, the following
4431 // isn't currently supported by this routine (in general):
4432 //
4433 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4434 //
4435 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4436 const char *semiBuf = strchr(startInitializerBuf, ';');
4437 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4438 SourceLocation semiLoc =
4439 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4440
4441 InsertText(semiLoc, "}");
4442 }
4443 return;
4444}
4445
4446void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4447 // Add initializers for any closure decl refs.
4448 GetBlockDeclRefExprs(Exp->getBody());
4449 if (BlockDeclRefs.size()) {
4450 // Unique all "by copy" declarations.
4451 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004452 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004453 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4454 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4455 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4456 }
4457 }
4458 // Unique all "by ref" declarations.
4459 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004460 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004461 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4462 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4463 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4464 }
4465 }
4466 // Find any imported blocks...they will need special attention.
4467 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004468 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004469 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4470 BlockDeclRefs[i]->getType()->isBlockPointerType())
4471 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4472 }
4473}
4474
4475FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4476 IdentifierInfo *ID = &Context->Idents.get(name);
4477 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4478 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4479 SourceLocation(), ID, FType, 0, SC_Extern,
4480 SC_None, false, false);
4481}
4482
4483Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004484 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004485 const BlockDecl *block = Exp->getBlockDecl();
4486 Blocks.push_back(Exp);
4487
4488 CollectBlockDeclRefInfo(Exp);
4489
4490 // Add inner imported variables now used in current block.
4491 int countOfInnerDecls = 0;
4492 if (!InnerBlockDeclRefs.empty()) {
4493 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004494 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004495 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004496 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004497 // We need to save the copied-in variables in nested
4498 // blocks because it is needed at the end for some of the API generations.
4499 // See SynthesizeBlockLiterals routine.
4500 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4501 BlockDeclRefs.push_back(Exp);
4502 BlockByCopyDeclsPtrSet.insert(VD);
4503 BlockByCopyDecls.push_back(VD);
4504 }
John McCallf4b88a42012-03-10 09:33:50 +00004505 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004506 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4507 BlockDeclRefs.push_back(Exp);
4508 BlockByRefDeclsPtrSet.insert(VD);
4509 BlockByRefDecls.push_back(VD);
4510 }
4511 }
4512 // Find any imported blocks...they will need special attention.
4513 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004514 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004515 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4516 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4517 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4518 }
4519 InnerDeclRefsCount.push_back(countOfInnerDecls);
4520
4521 std::string FuncName;
4522
4523 if (CurFunctionDef)
4524 FuncName = CurFunctionDef->getNameAsString();
4525 else if (CurMethodDef)
4526 BuildUniqueMethodName(FuncName, CurMethodDef);
4527 else if (GlobalVarDecl)
4528 FuncName = std::string(GlobalVarDecl->getNameAsString());
4529
4530 std::string BlockNumber = utostr(Blocks.size()-1);
4531
4532 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4533 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4534
4535 // Get a pointer to the function type so we can cast appropriately.
4536 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4537 QualType FType = Context->getPointerType(BFT);
4538
4539 FunctionDecl *FD;
4540 Expr *NewRep;
4541
4542 // Simulate a contructor call...
4543 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004544 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004545 SourceLocation());
4546
4547 SmallVector<Expr*, 4> InitExprs;
4548
4549 // Initialize the block function.
4550 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004551 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4552 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004553 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4554 CK_BitCast, Arg);
4555 InitExprs.push_back(castExpr);
4556
4557 // Initialize the block descriptor.
4558 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4559
4560 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4561 SourceLocation(), SourceLocation(),
4562 &Context->Idents.get(DescData.c_str()),
4563 Context->VoidPtrTy, 0,
4564 SC_Static, SC_None);
4565 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004566 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004567 Context->VoidPtrTy,
4568 VK_LValue,
4569 SourceLocation()),
4570 UO_AddrOf,
4571 Context->getPointerType(Context->VoidPtrTy),
4572 VK_RValue, OK_Ordinary,
4573 SourceLocation());
4574 InitExprs.push_back(DescRefExpr);
4575
4576 // Add initializers for any closure decl refs.
4577 if (BlockDeclRefs.size()) {
4578 Expr *Exp;
4579 // Output all "by copy" declarations.
4580 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4581 E = BlockByCopyDecls.end(); I != E; ++I) {
4582 if (isObjCType((*I)->getType())) {
4583 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4584 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004585 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4586 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004587 if (HasLocalVariableExternalStorage(*I)) {
4588 QualType QT = (*I)->getType();
4589 QT = Context->getPointerType(QT);
4590 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4591 OK_Ordinary, SourceLocation());
4592 }
4593 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4594 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004595 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4596 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004597 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4598 CK_BitCast, Arg);
4599 } else {
4600 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004601 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4602 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004603 if (HasLocalVariableExternalStorage(*I)) {
4604 QualType QT = (*I)->getType();
4605 QT = Context->getPointerType(QT);
4606 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4607 OK_Ordinary, SourceLocation());
4608 }
4609
4610 }
4611 InitExprs.push_back(Exp);
4612 }
4613 // Output all "by ref" declarations.
4614 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4615 E = BlockByRefDecls.end(); I != E; ++I) {
4616 ValueDecl *ND = (*I);
4617 std::string Name(ND->getNameAsString());
4618 std::string RecName;
4619 RewriteByRefString(RecName, Name, ND, true);
4620 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4621 + sizeof("struct"));
4622 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4623 SourceLocation(), SourceLocation(),
4624 II);
4625 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4626 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4627
4628 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004629 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004630 SourceLocation());
4631 bool isNestedCapturedVar = false;
4632 if (block)
4633 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4634 ce = block->capture_end(); ci != ce; ++ci) {
4635 const VarDecl *variable = ci->getVariable();
4636 if (variable == ND && ci->isNested()) {
4637 assert (ci->isByRef() &&
4638 "SynthBlockInitExpr - captured block variable is not byref");
4639 isNestedCapturedVar = true;
4640 break;
4641 }
4642 }
4643 // captured nested byref variable has its address passed. Do not take
4644 // its address again.
4645 if (!isNestedCapturedVar)
4646 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4647 Context->getPointerType(Exp->getType()),
4648 VK_RValue, OK_Ordinary, SourceLocation());
4649 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4650 InitExprs.push_back(Exp);
4651 }
4652 }
4653 if (ImportedBlockDecls.size()) {
4654 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4655 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4656 unsigned IntSize =
4657 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4658 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4659 Context->IntTy, SourceLocation());
4660 InitExprs.push_back(FlagExp);
4661 }
4662 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4663 FType, VK_LValue, SourceLocation());
4664 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4665 Context->getPointerType(NewRep->getType()),
4666 VK_RValue, OK_Ordinary, SourceLocation());
4667 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4668 NewRep);
4669 BlockDeclRefs.clear();
4670 BlockByRefDecls.clear();
4671 BlockByRefDeclsPtrSet.clear();
4672 BlockByCopyDecls.clear();
4673 BlockByCopyDeclsPtrSet.clear();
4674 ImportedBlockDecls.clear();
4675 return NewRep;
4676}
4677
4678bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4679 if (const ObjCForCollectionStmt * CS =
4680 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4681 return CS->getElement() == DS;
4682 return false;
4683}
4684
4685//===----------------------------------------------------------------------===//
4686// Function Body / Expression rewriting
4687//===----------------------------------------------------------------------===//
4688
4689Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4690 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4691 isa<DoStmt>(S) || isa<ForStmt>(S))
4692 Stmts.push_back(S);
4693 else if (isa<ObjCForCollectionStmt>(S)) {
4694 Stmts.push_back(S);
4695 ObjCBcLabelNo.push_back(++BcLabelCount);
4696 }
4697
4698 // Pseudo-object operations and ivar references need special
4699 // treatment because we're going to recursively rewrite them.
4700 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4701 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4702 return RewritePropertyOrImplicitSetter(PseudoOp);
4703 } else {
4704 return RewritePropertyOrImplicitGetter(PseudoOp);
4705 }
4706 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4707 return RewriteObjCIvarRefExpr(IvarRefExpr);
4708 }
4709
4710 SourceRange OrigStmtRange = S->getSourceRange();
4711
4712 // Perform a bottom up rewrite of all children.
4713 for (Stmt::child_range CI = S->children(); CI; ++CI)
4714 if (*CI) {
4715 Stmt *childStmt = (*CI);
4716 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4717 if (newStmt) {
4718 *CI = newStmt;
4719 }
4720 }
4721
4722 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004723 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004724 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4725 InnerContexts.insert(BE->getBlockDecl());
4726 ImportedLocalExternalDecls.clear();
4727 GetInnerBlockDeclRefExprs(BE->getBody(),
4728 InnerBlockDeclRefs, InnerContexts);
4729 // Rewrite the block body in place.
4730 Stmt *SaveCurrentBody = CurrentBody;
4731 CurrentBody = BE->getBody();
4732 PropParentMap = 0;
4733 // block literal on rhs of a property-dot-sytax assignment
4734 // must be replaced by its synthesize ast so getRewrittenText
4735 // works as expected. In this case, what actually ends up on RHS
4736 // is the blockTranscribed which is the helper function for the
4737 // block literal; as in: self.c = ^() {[ace ARR];};
4738 bool saveDisableReplaceStmt = DisableReplaceStmt;
4739 DisableReplaceStmt = false;
4740 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4741 DisableReplaceStmt = saveDisableReplaceStmt;
4742 CurrentBody = SaveCurrentBody;
4743 PropParentMap = 0;
4744 ImportedLocalExternalDecls.clear();
4745 // Now we snarf the rewritten text and stash it away for later use.
4746 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4747 RewrittenBlockExprs[BE] = Str;
4748
4749 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4750
4751 //blockTranscribed->dump();
4752 ReplaceStmt(S, blockTranscribed);
4753 return blockTranscribed;
4754 }
4755 // Handle specific things.
4756 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4757 return RewriteAtEncode(AtEncode);
4758
4759 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4760 return RewriteAtSelector(AtSelector);
4761
4762 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4763 return RewriteObjCStringLiteral(AtString);
4764
4765 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4766#if 0
4767 // Before we rewrite it, put the original message expression in a comment.
4768 SourceLocation startLoc = MessExpr->getLocStart();
4769 SourceLocation endLoc = MessExpr->getLocEnd();
4770
4771 const char *startBuf = SM->getCharacterData(startLoc);
4772 const char *endBuf = SM->getCharacterData(endLoc);
4773
4774 std::string messString;
4775 messString += "// ";
4776 messString.append(startBuf, endBuf-startBuf+1);
4777 messString += "\n";
4778
4779 // FIXME: Missing definition of
4780 // InsertText(clang::SourceLocation, char const*, unsigned int).
4781 // InsertText(startLoc, messString.c_str(), messString.size());
4782 // Tried this, but it didn't work either...
4783 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4784#endif
4785 return RewriteMessageExpr(MessExpr);
4786 }
4787
4788 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4789 return RewriteObjCTryStmt(StmtTry);
4790
4791 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4792 return RewriteObjCSynchronizedStmt(StmtTry);
4793
4794 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4795 return RewriteObjCThrowStmt(StmtThrow);
4796
4797 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4798 return RewriteObjCProtocolExpr(ProtocolExp);
4799
4800 if (ObjCForCollectionStmt *StmtForCollection =
4801 dyn_cast<ObjCForCollectionStmt>(S))
4802 return RewriteObjCForCollectionStmt(StmtForCollection,
4803 OrigStmtRange.getEnd());
4804 if (BreakStmt *StmtBreakStmt =
4805 dyn_cast<BreakStmt>(S))
4806 return RewriteBreakStmt(StmtBreakStmt);
4807 if (ContinueStmt *StmtContinueStmt =
4808 dyn_cast<ContinueStmt>(S))
4809 return RewriteContinueStmt(StmtContinueStmt);
4810
4811 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4812 // and cast exprs.
4813 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4814 // FIXME: What we're doing here is modifying the type-specifier that
4815 // precedes the first Decl. In the future the DeclGroup should have
4816 // a separate type-specifier that we can rewrite.
4817 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4818 // the context of an ObjCForCollectionStmt. For example:
4819 // NSArray *someArray;
4820 // for (id <FooProtocol> index in someArray) ;
4821 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4822 // and it depends on the original text locations/positions.
4823 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4824 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4825
4826 // Blocks rewrite rules.
4827 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4828 DI != DE; ++DI) {
4829 Decl *SD = *DI;
4830 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4831 if (isTopLevelBlockPointerType(ND->getType()))
4832 RewriteBlockPointerDecl(ND);
4833 else if (ND->getType()->isFunctionPointerType())
4834 CheckFunctionPointerDecl(ND->getType(), ND);
4835 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4836 if (VD->hasAttr<BlocksAttr>()) {
4837 static unsigned uniqueByrefDeclCount = 0;
4838 assert(!BlockByRefDeclNo.count(ND) &&
4839 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4840 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4841 RewriteByRefVar(VD);
4842 }
4843 else
4844 RewriteTypeOfDecl(VD);
4845 }
4846 }
4847 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4848 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4849 RewriteBlockPointerDecl(TD);
4850 else if (TD->getUnderlyingType()->isFunctionPointerType())
4851 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4852 }
4853 }
4854 }
4855
4856 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4857 RewriteObjCQualifiedInterfaceTypes(CE);
4858
4859 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4860 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4861 assert(!Stmts.empty() && "Statement stack is empty");
4862 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4863 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4864 && "Statement stack mismatch");
4865 Stmts.pop_back();
4866 }
4867 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004868 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4869 ValueDecl *VD = DRE->getDecl();
4870 if (VD->hasAttr<BlocksAttr>())
4871 return RewriteBlockDeclRefExpr(DRE);
4872 if (HasLocalVariableExternalStorage(VD))
4873 return RewriteLocalVariableExternalStorage(DRE);
4874 }
4875
4876 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4877 if (CE->getCallee()->getType()->isBlockPointerType()) {
4878 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4879 ReplaceStmt(S, BlockCall);
4880 return BlockCall;
4881 }
4882 }
4883 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4884 RewriteCastExpr(CE);
4885 }
4886#if 0
4887 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4888 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4889 ICE->getSubExpr(),
4890 SourceLocation());
4891 // Get the new text.
4892 std::string SStr;
4893 llvm::raw_string_ostream Buf(SStr);
4894 Replacement->printPretty(Buf, *Context);
4895 const std::string &Str = Buf.str();
4896
4897 printf("CAST = %s\n", &Str[0]);
4898 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4899 delete S;
4900 return Replacement;
4901 }
4902#endif
4903 // Return this stmt unmodified.
4904 return S;
4905}
4906
4907void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4908 for (RecordDecl::field_iterator i = RD->field_begin(),
4909 e = RD->field_end(); i != e; ++i) {
4910 FieldDecl *FD = *i;
4911 if (isTopLevelBlockPointerType(FD->getType()))
4912 RewriteBlockPointerDecl(FD);
4913 if (FD->getType()->isObjCQualifiedIdType() ||
4914 FD->getType()->isObjCQualifiedInterfaceType())
4915 RewriteObjCQualifiedInterfaceTypes(FD);
4916 }
4917}
4918
4919/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4920/// main file of the input.
4921void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4922 switch (D->getKind()) {
4923 case Decl::Function: {
4924 FunctionDecl *FD = cast<FunctionDecl>(D);
4925 if (FD->isOverloadedOperator())
4926 return;
4927
4928 // Since function prototypes don't have ParmDecl's, we check the function
4929 // prototype. This enables us to rewrite function declarations and
4930 // definitions using the same code.
4931 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4932
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004933 if (!FD->isThisDeclarationADefinition())
4934 break;
4935
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004936 // FIXME: If this should support Obj-C++, support CXXTryStmt
4937 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4938 CurFunctionDef = FD;
4939 CurFunctionDeclToDeclareForBlock = FD;
4940 CurrentBody = Body;
4941 Body =
4942 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4943 FD->setBody(Body);
4944 CurrentBody = 0;
4945 if (PropParentMap) {
4946 delete PropParentMap;
4947 PropParentMap = 0;
4948 }
4949 // This synthesizes and inserts the block "impl" struct, invoke function,
4950 // and any copy/dispose helper functions.
4951 InsertBlockLiteralsWithinFunction(FD);
4952 CurFunctionDef = 0;
4953 CurFunctionDeclToDeclareForBlock = 0;
4954 }
4955 break;
4956 }
4957 case Decl::ObjCMethod: {
4958 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4959 if (CompoundStmt *Body = MD->getCompoundBody()) {
4960 CurMethodDef = MD;
4961 CurrentBody = Body;
4962 Body =
4963 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4964 MD->setBody(Body);
4965 CurrentBody = 0;
4966 if (PropParentMap) {
4967 delete PropParentMap;
4968 PropParentMap = 0;
4969 }
4970 InsertBlockLiteralsWithinMethod(MD);
4971 CurMethodDef = 0;
4972 }
4973 break;
4974 }
4975 case Decl::ObjCImplementation: {
4976 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4977 ClassImplementation.push_back(CI);
4978 break;
4979 }
4980 case Decl::ObjCCategoryImpl: {
4981 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4982 CategoryImplementation.push_back(CI);
4983 break;
4984 }
4985 case Decl::Var: {
4986 VarDecl *VD = cast<VarDecl>(D);
4987 RewriteObjCQualifiedInterfaceTypes(VD);
4988 if (isTopLevelBlockPointerType(VD->getType()))
4989 RewriteBlockPointerDecl(VD);
4990 else if (VD->getType()->isFunctionPointerType()) {
4991 CheckFunctionPointerDecl(VD->getType(), VD);
4992 if (VD->getInit()) {
4993 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4994 RewriteCastExpr(CE);
4995 }
4996 }
4997 } else if (VD->getType()->isRecordType()) {
4998 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4999 if (RD->isCompleteDefinition())
5000 RewriteRecordBody(RD);
5001 }
5002 if (VD->getInit()) {
5003 GlobalVarDecl = VD;
5004 CurrentBody = VD->getInit();
5005 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5006 CurrentBody = 0;
5007 if (PropParentMap) {
5008 delete PropParentMap;
5009 PropParentMap = 0;
5010 }
5011 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5012 GlobalVarDecl = 0;
5013
5014 // This is needed for blocks.
5015 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5016 RewriteCastExpr(CE);
5017 }
5018 }
5019 break;
5020 }
5021 case Decl::TypeAlias:
5022 case Decl::Typedef: {
5023 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5024 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5025 RewriteBlockPointerDecl(TD);
5026 else if (TD->getUnderlyingType()->isFunctionPointerType())
5027 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5028 }
5029 break;
5030 }
5031 case Decl::CXXRecord:
5032 case Decl::Record: {
5033 RecordDecl *RD = cast<RecordDecl>(D);
5034 if (RD->isCompleteDefinition())
5035 RewriteRecordBody(RD);
5036 break;
5037 }
5038 default:
5039 break;
5040 }
5041 // Nothing yet.
5042}
5043
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005044/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5045/// protocol reference symbols in the for of:
5046/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5047static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5048 ObjCProtocolDecl *PDecl,
5049 std::string &Result) {
5050 // Also output .objc_protorefs$B section and its meta-data.
5051 if (Context->getLangOpts().MicrosoftExt)
5052 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5053 Result += "struct _protocol_t *";
5054 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5055 Result += PDecl->getNameAsString();
5056 Result += " = &";
5057 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5058 Result += ";\n";
5059}
5060
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005061void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5062 if (Diags.hasErrorOccurred())
5063 return;
5064
5065 RewriteInclude();
5066
5067 // Here's a great place to add any extra declarations that may be needed.
5068 // Write out meta data for each @protocol(<expr>).
5069 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005070 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005071 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005072 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5073 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005074
5075 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005076 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5077 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5078 // Write struct declaration for the class matching its ivar declarations.
5079 // Note that for modern abi, this is postponed until the end of TU
5080 // because class extensions and the implementation might declare their own
5081 // private ivars.
5082 RewriteInterfaceDecl(CDecl);
5083 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005084
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005085 if (ClassImplementation.size() || CategoryImplementation.size())
5086 RewriteImplementations();
5087
5088 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5089 // we are done.
5090 if (const RewriteBuffer *RewriteBuf =
5091 Rewrite.getRewriteBufferFor(MainFileID)) {
5092 //printf("Changed:\n");
5093 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5094 } else {
5095 llvm::errs() << "No changes\n";
5096 }
5097
5098 if (ClassImplementation.size() || CategoryImplementation.size() ||
5099 ProtocolExprDecls.size()) {
5100 // Rewrite Objective-c meta data*
5101 std::string ResultStr;
5102 RewriteMetaDataIntoBuffer(ResultStr);
5103 // Emit metadata.
5104 *OutFile << ResultStr;
5105 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005106 // Emit ImageInfo;
5107 {
5108 std::string ResultStr;
5109 WriteImageInfo(ResultStr);
5110 *OutFile << ResultStr;
5111 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005112 OutFile->flush();
5113}
5114
5115void RewriteModernObjC::Initialize(ASTContext &context) {
5116 InitializeCommon(context);
5117
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005118 Preamble += "#ifndef __OBJC2__\n";
5119 Preamble += "#define __OBJC2__\n";
5120 Preamble += "#endif\n";
5121
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005122 // declaring objc_selector outside the parameter list removes a silly
5123 // scope related warning...
5124 if (IsHeader)
5125 Preamble = "#pragma once\n";
5126 Preamble += "struct objc_selector; struct objc_class;\n";
5127 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5128 Preamble += "struct objc_object *superClass; ";
5129 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005130 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005131 // These are currently generated.
5132 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005133 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005134 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5135 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005136 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5137 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005138 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005139 // These are generated but not necessary for functionality.
5140 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5141 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005142 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5143 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005144 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005145
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005146 // These need be generated for performance. Currently they are not,
5147 // using API calls instead.
5148 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5149 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5150 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5151
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005152 // Add a constructor for creating temporary objects.
5153 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5154 ": ";
5155 Preamble += "object(o), superClass(s) {} ";
5156 }
5157 Preamble += "};\n";
5158 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5159 Preamble += "typedef struct objc_object Protocol;\n";
5160 Preamble += "#define _REWRITER_typedef_Protocol\n";
5161 Preamble += "#endif\n";
5162 if (LangOpts.MicrosoftExt) {
5163 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5164 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5165 } else
5166 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5167 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5168 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5169 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5170 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5171 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5172 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5173 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5174 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5175 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5176 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5177 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5178 Preamble += "(const char *);\n";
5179 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5180 Preamble += "(struct objc_class *);\n";
5181 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5182 Preamble += "(const char *);\n";
Fariborz Jahanianb1228182012-03-15 22:42:15 +00005183 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(id);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005184 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5185 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5186 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5187 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5188 Preamble += "(struct objc_class *, struct objc_object *);\n";
5189 // @synchronized hooks.
5190 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5191 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5192 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5193 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5194 Preamble += "struct __objcFastEnumerationState {\n\t";
5195 Preamble += "unsigned long state;\n\t";
5196 Preamble += "void **itemsPtr;\n\t";
5197 Preamble += "unsigned long *mutationsPtr;\n\t";
5198 Preamble += "unsigned long extra[5];\n};\n";
5199 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5200 Preamble += "#define __FASTENUMERATIONSTATE\n";
5201 Preamble += "#endif\n";
5202 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5203 Preamble += "struct __NSConstantStringImpl {\n";
5204 Preamble += " int *isa;\n";
5205 Preamble += " int flags;\n";
5206 Preamble += " char *str;\n";
5207 Preamble += " long length;\n";
5208 Preamble += "};\n";
5209 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5210 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5211 Preamble += "#else\n";
5212 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5213 Preamble += "#endif\n";
5214 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5215 Preamble += "#endif\n";
5216 // Blocks preamble.
5217 Preamble += "#ifndef BLOCK_IMPL\n";
5218 Preamble += "#define BLOCK_IMPL\n";
5219 Preamble += "struct __block_impl {\n";
5220 Preamble += " void *isa;\n";
5221 Preamble += " int Flags;\n";
5222 Preamble += " int Reserved;\n";
5223 Preamble += " void *FuncPtr;\n";
5224 Preamble += "};\n";
5225 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5226 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5227 Preamble += "extern \"C\" __declspec(dllexport) "
5228 "void _Block_object_assign(void *, const void *, const int);\n";
5229 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5230 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5231 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5232 Preamble += "#else\n";
5233 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5234 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5235 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5236 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5237 Preamble += "#endif\n";
5238 Preamble += "#endif\n";
5239 if (LangOpts.MicrosoftExt) {
5240 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5241 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5242 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5243 Preamble += "#define __attribute__(X)\n";
5244 Preamble += "#endif\n";
5245 Preamble += "#define __weak\n";
5246 }
5247 else {
5248 Preamble += "#define __block\n";
5249 Preamble += "#define __weak\n";
5250 }
5251 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5252 // as this avoids warning in any 64bit/32bit compilation model.
5253 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5254}
5255
5256/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5257/// ivar offset.
5258void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5259 std::string &Result) {
5260 if (ivar->isBitField()) {
5261 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5262 // place all bitfields at offset 0.
5263 Result += "0";
5264 } else {
5265 Result += "__OFFSETOFIVAR__(struct ";
5266 Result += ivar->getContainingInterface()->getNameAsString();
5267 if (LangOpts.MicrosoftExt)
5268 Result += "_IMPL";
5269 Result += ", ";
5270 Result += ivar->getNameAsString();
5271 Result += ")";
5272 }
5273}
5274
5275/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5276/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005277/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005278/// char *attributes;
5279/// }
5280
5281/// struct _prop_list_t {
5282/// uint32_t entsize; // sizeof(struct _prop_t)
5283/// uint32_t count_of_properties;
5284/// struct _prop_t prop_list[count_of_properties];
5285/// }
5286
5287/// struct _protocol_t;
5288
5289/// struct _protocol_list_t {
5290/// long protocol_count; // Note, this is 32/64 bit
5291/// struct _protocol_t * protocol_list[protocol_count];
5292/// }
5293
5294/// struct _objc_method {
5295/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005296/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005297/// char *_imp;
5298/// }
5299
5300/// struct _method_list_t {
5301/// uint32_t entsize; // sizeof(struct _objc_method)
5302/// uint32_t method_count;
5303/// struct _objc_method method_list[method_count];
5304/// }
5305
5306/// struct _protocol_t {
5307/// id isa; // NULL
5308/// const char * const protocol_name;
5309/// const struct _protocol_list_t * protocol_list; // super protocols
5310/// const struct method_list_t * const instance_methods;
5311/// const struct method_list_t * const class_methods;
5312/// const struct method_list_t *optionalInstanceMethods;
5313/// const struct method_list_t *optionalClassMethods;
5314/// const struct _prop_list_t * properties;
5315/// const uint32_t size; // sizeof(struct _protocol_t)
5316/// const uint32_t flags; // = 0
5317/// const char ** extendedMethodTypes;
5318/// }
5319
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005320/// struct _ivar_t {
5321/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005322/// const char *name;
5323/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005324/// uint32_t alignment;
5325/// uint32_t size;
5326/// }
5327
5328/// struct _ivar_list_t {
5329/// uint32 entsize; // sizeof(struct _ivar_t)
5330/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005331/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005332/// }
5333
5334/// struct _class_ro_t {
5335/// uint32_t const flags;
5336/// uint32_t const instanceStart;
5337/// uint32_t const instanceSize;
5338/// uint32_t const reserved; // only when building for 64bit targets
5339/// const uint8_t * const ivarLayout;
5340/// const char *const name;
5341/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005342/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005343/// const struct _ivar_list_t *const ivars;
5344/// const uint8_t * const weakIvarLayout;
5345/// const struct _prop_list_t * const properties;
5346/// }
5347
5348/// struct _class_t {
5349/// struct _class_t *isa;
5350/// struct _class_t * const superclass;
5351/// void *cache;
5352/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005353/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005354/// }
5355
5356/// struct _category_t {
5357/// const char * const name;
5358/// struct _class_t *const cls;
5359/// const struct _method_list_t * const instance_methods;
5360/// const struct _method_list_t * const class_methods;
5361/// const struct _protocol_list_t * const protocols;
5362/// const struct _prop_list_t * const properties;
5363/// }
5364
5365/// MessageRefTy - LLVM for:
5366/// struct _message_ref_t {
5367/// IMP messenger;
5368/// SEL name;
5369/// };
5370
5371/// SuperMessageRefTy - LLVM for:
5372/// struct _super_message_ref_t {
5373/// SUPER_IMP messenger;
5374/// SEL name;
5375/// };
5376
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005377static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005378 static bool meta_data_declared = false;
5379 if (meta_data_declared)
5380 return;
5381
5382 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005383 Result += "\tconst char *name;\n";
5384 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005385 Result += "};\n";
5386
5387 Result += "\nstruct _protocol_t;\n";
5388
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005389 Result += "\nstruct _objc_method {\n";
5390 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005391 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005392 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005393 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005394
5395 Result += "\nstruct _protocol_t {\n";
5396 Result += "\tvoid * isa; // NULL\n";
5397 Result += "\tconst char * const protocol_name;\n";
5398 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5399 Result += "\tconst struct method_list_t * const instance_methods;\n";
5400 Result += "\tconst struct method_list_t * const class_methods;\n";
5401 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5402 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5403 Result += "\tconst struct _prop_list_t * properties;\n";
5404 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5405 Result += "\tconst unsigned int flags; // = 0\n";
5406 Result += "\tconst char ** extendedMethodTypes;\n";
5407 Result += "};\n";
5408
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005409 Result += "\nstruct _ivar_t {\n";
5410 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005411 Result += "\tconst char *name;\n";
5412 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005413 Result += "\tunsigned int alignment;\n";
5414 Result += "\tunsigned int size;\n";
5415 Result += "};\n";
5416
5417 Result += "\nstruct _class_ro_t {\n";
5418 Result += "\tunsigned int const flags;\n";
5419 Result += "\tunsigned int instanceStart;\n";
5420 Result += "\tunsigned int const instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005421 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5422 if (Triple.getArch() == llvm::Triple::x86_64)
5423 Result += "\tunsigned int const reserved;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005424 Result += "\tconst unsigned char * const ivarLayout;\n";
5425 Result += "\tconst char *const name;\n";
5426 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5427 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5428 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5429 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5430 Result += "\tconst struct _prop_list_t *const properties;\n";
5431 Result += "};\n";
5432
5433 Result += "\nstruct _class_t {\n";
5434 Result += "\tstruct _class_t *isa;\n";
5435 Result += "\tstruct _class_t *const superclass;\n";
5436 Result += "\tvoid *cache;\n";
5437 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005438 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005439 Result += "};\n";
5440
5441 Result += "\nstruct _category_t {\n";
5442 Result += "\tconst char * const name;\n";
5443 Result += "\tstruct _class_t *const cls;\n";
5444 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5445 Result += "\tconst struct _method_list_t *const class_methods;\n";
5446 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5447 Result += "\tconst struct _prop_list_t *const properties;\n";
5448 Result += "};\n";
5449
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005450 Result += "extern void *_objc_empty_cache;\n";
5451 Result += "extern void *_objc_empty_vtable;\n";
5452
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005453 meta_data_declared = true;
5454}
5455
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005456static void Write_protocol_list_t_TypeDecl(std::string &Result,
5457 long super_protocol_count) {
5458 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5459 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5460 Result += "\tstruct _protocol_t *super_protocols[";
5461 Result += utostr(super_protocol_count); Result += "];\n";
5462 Result += "}";
5463}
5464
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005465static void Write_method_list_t_TypeDecl(std::string &Result,
5466 unsigned int method_count) {
5467 Result += "struct /*_method_list_t*/"; Result += " {\n";
5468 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5469 Result += "\tunsigned int method_count;\n";
5470 Result += "\tstruct _objc_method method_list[";
5471 Result += utostr(method_count); Result += "];\n";
5472 Result += "}";
5473}
5474
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005475static void Write__prop_list_t_TypeDecl(std::string &Result,
5476 unsigned int property_count) {
5477 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5478 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5479 Result += "\tunsigned int count_of_properties;\n";
5480 Result += "\tstruct _prop_t prop_list[";
5481 Result += utostr(property_count); Result += "];\n";
5482 Result += "}";
5483}
5484
Fariborz Jahanianae932952012-02-10 20:47:10 +00005485static void Write__ivar_list_t_TypeDecl(std::string &Result,
5486 unsigned int ivar_count) {
5487 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5488 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5489 Result += "\tunsigned int count;\n";
5490 Result += "\tstruct _ivar_t ivar_list[";
5491 Result += utostr(ivar_count); Result += "];\n";
5492 Result += "}";
5493}
5494
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005495static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5496 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5497 StringRef VarName,
5498 StringRef ProtocolName) {
5499 if (SuperProtocols.size() > 0) {
5500 Result += "\nstatic ";
5501 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5502 Result += " "; Result += VarName;
5503 Result += ProtocolName;
5504 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5505 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5506 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5507 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5508 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5509 Result += SuperPD->getNameAsString();
5510 if (i == e-1)
5511 Result += "\n};\n";
5512 else
5513 Result += ",\n";
5514 }
5515 }
5516}
5517
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005518static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5519 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005520 ArrayRef<ObjCMethodDecl *> Methods,
5521 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005522 StringRef TopLevelDeclName,
5523 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005524 if (Methods.size() > 0) {
5525 Result += "\nstatic ";
5526 Write_method_list_t_TypeDecl(Result, Methods.size());
5527 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005528 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005529 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5530 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5531 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5532 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5533 ObjCMethodDecl *MD = Methods[i];
5534 if (i == 0)
5535 Result += "\t{{(struct objc_selector *)\"";
5536 else
5537 Result += "\t{(struct objc_selector *)\"";
5538 Result += (MD)->getSelector().getAsString(); Result += "\"";
5539 Result += ", ";
5540 std::string MethodTypeString;
5541 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5542 Result += "\""; Result += MethodTypeString; Result += "\"";
5543 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005544 if (!MethodImpl)
5545 Result += "0";
5546 else {
5547 Result += "(void *)";
5548 Result += RewriteObj.MethodInternalNames[MD];
5549 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005550 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005551 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005552 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005553 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005554 }
5555 Result += "};\n";
5556 }
5557}
5558
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005559static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005560 ASTContext *Context, std::string &Result,
5561 ArrayRef<ObjCPropertyDecl *> Properties,
5562 const Decl *Container,
5563 StringRef VarName,
5564 StringRef ProtocolName) {
5565 if (Properties.size() > 0) {
5566 Result += "\nstatic ";
5567 Write__prop_list_t_TypeDecl(Result, Properties.size());
5568 Result += " "; Result += VarName;
5569 Result += ProtocolName;
5570 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5571 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5572 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5573 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5574 ObjCPropertyDecl *PropDecl = Properties[i];
5575 if (i == 0)
5576 Result += "\t{{\"";
5577 else
5578 Result += "\t{\"";
5579 Result += PropDecl->getName(); Result += "\",";
5580 std::string PropertyTypeString, QuotePropertyTypeString;
5581 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5582 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5583 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5584 if (i == e-1)
5585 Result += "}}\n";
5586 else
5587 Result += "},\n";
5588 }
5589 Result += "};\n";
5590 }
5591}
5592
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005593// Metadata flags
5594enum MetaDataDlags {
5595 CLS = 0x0,
5596 CLS_META = 0x1,
5597 CLS_ROOT = 0x2,
5598 OBJC2_CLS_HIDDEN = 0x10,
5599 CLS_EXCEPTION = 0x20,
5600
5601 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5602 CLS_HAS_IVAR_RELEASER = 0x40,
5603 /// class was compiled with -fobjc-arr
5604 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5605};
5606
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005607static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5608 unsigned int flags,
5609 const std::string &InstanceStart,
5610 const std::string &InstanceSize,
5611 ArrayRef<ObjCMethodDecl *>baseMethods,
5612 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5613 ArrayRef<ObjCIvarDecl *>ivars,
5614 ArrayRef<ObjCPropertyDecl *>Properties,
5615 StringRef VarName,
5616 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005617 Result += "\nstatic struct _class_ro_t ";
5618 Result += VarName; Result += ClassName;
5619 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5620 Result += "\t";
5621 Result += llvm::utostr(flags); Result += ", ";
5622 Result += InstanceStart; Result += ", ";
5623 Result += InstanceSize; Result += ", \n";
5624 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005625 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5626 if (Triple.getArch() == llvm::Triple::x86_64)
5627 // uint32_t const reserved; // only when building for 64bit targets
5628 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005629 // const uint8_t * const ivarLayout;
5630 Result += "0, \n\t";
5631 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005632 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005633 if (baseMethods.size() > 0) {
5634 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005635 if (metaclass)
5636 Result += "_OBJC_$_CLASS_METHODS_";
5637 else
5638 Result += "_OBJC_$_INSTANCE_METHODS_";
5639 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005640 Result += ",\n\t";
5641 }
5642 else
5643 Result += "0, \n\t";
5644
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005645 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005646 Result += "(const struct _objc_protocol_list *)&";
5647 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5648 Result += ",\n\t";
5649 }
5650 else
5651 Result += "0, \n\t";
5652
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005653 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005654 Result += "(const struct _ivar_list_t *)&";
5655 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5656 Result += ",\n\t";
5657 }
5658 else
5659 Result += "0, \n\t";
5660
5661 // weakIvarLayout
5662 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005663 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005664 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005665 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005666 Result += ",\n";
5667 }
5668 else
5669 Result += "0, \n";
5670
5671 Result += "};\n";
5672}
5673
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005674static void Write_class_t(ASTContext *Context, std::string &Result,
5675 StringRef VarName,
5676 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005677
5678 if (metadata && !CDecl->getSuperClass()) {
5679 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005680 Result += "\n";
5681 if (CDecl->getImplementation())
5682 Result += "__declspec(dllexport) ";
5683 Result += "extern struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005684 Result += CDecl->getNameAsString();
5685 Result += ";\n";
5686 }
5687 // Also, for possibility of 'super' metadata class not having been defined yet.
5688 if (CDecl->getSuperClass()) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005689 Result += "\n";
5690 if (CDecl->getSuperClass()->getImplementation())
5691 Result += "__declspec(dllexport) ";
5692 Result += "extern struct _class_t ";
5693 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005694 Result += CDecl->getSuperClass()->getNameAsString();
5695 Result += ";\n";
5696 }
5697
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005698 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005699 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5700 Result += "\t";
5701 if (metadata) {
5702 if (CDecl->getSuperClass()) {
5703 Result += "&"; Result += VarName;
5704 Result += CDecl->getSuperClass()->getNameAsString();
5705 Result += ",\n\t";
5706 Result += "&"; Result += VarName;
5707 Result += CDecl->getSuperClass()->getNameAsString();
5708 Result += ",\n\t";
5709 }
5710 else {
5711 Result += "&"; Result += VarName;
5712 Result += CDecl->getNameAsString();
5713 Result += ",\n\t";
5714 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5715 Result += ",\n\t";
5716 }
5717 }
5718 else {
5719 Result += "&OBJC_METACLASS_$_";
5720 Result += CDecl->getNameAsString();
5721 Result += ",\n\t";
5722 if (CDecl->getSuperClass()) {
5723 Result += "&"; Result += VarName;
5724 Result += CDecl->getSuperClass()->getNameAsString();
5725 Result += ",\n\t";
5726 }
5727 else
5728 Result += "0,\n\t";
5729 }
5730 Result += "(void *)&_objc_empty_cache,\n\t";
5731 Result += "(void *)&_objc_empty_vtable,\n\t";
5732 if (metadata)
5733 Result += "&_OBJC_METACLASS_RO_$_";
5734 else
5735 Result += "&_OBJC_CLASS_RO_$_";
5736 Result += CDecl->getNameAsString();
5737 Result += ",\n};\n";
5738}
5739
Fariborz Jahanian61186122012-02-17 18:40:41 +00005740static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5741 std::string &Result,
5742 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005743 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005744 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5745 ArrayRef<ObjCMethodDecl *> ClassMethods,
5746 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5747 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005748
5749 StringRef ClassName = ClassDecl->getNameAsString();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005750 // must declare an extern class object in case this class is not implemented
5751 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005752 Result += "\n";
5753 if (ClassDecl->getImplementation())
5754 Result += "__declspec(dllexport) ";
5755
5756 Result += "extern struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005757 Result += "OBJC_CLASS_$_"; Result += ClassName;
5758 Result += ";\n";
5759
Fariborz Jahanian61186122012-02-17 18:40:41 +00005760 Result += "\nstatic struct _category_t ";
5761 Result += "_OBJC_$_CATEGORY_";
5762 Result += ClassName; Result += "_$_"; Result += CatName;
5763 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5764 Result += "{\n";
5765 Result += "\t\""; Result += ClassName; Result += "\",\n";
5766 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5767 Result += ",\n";
5768 if (InstanceMethods.size() > 0) {
5769 Result += "\t(const struct _method_list_t *)&";
5770 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5771 Result += ClassName; Result += "_$_"; Result += CatName;
5772 Result += ",\n";
5773 }
5774 else
5775 Result += "\t0,\n";
5776
5777 if (ClassMethods.size() > 0) {
5778 Result += "\t(const struct _method_list_t *)&";
5779 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5780 Result += ClassName; Result += "_$_"; Result += CatName;
5781 Result += ",\n";
5782 }
5783 else
5784 Result += "\t0,\n";
5785
5786 if (RefedProtocols.size() > 0) {
5787 Result += "\t(const struct _protocol_list_t *)&";
5788 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5789 Result += ClassName; Result += "_$_"; Result += CatName;
5790 Result += ",\n";
5791 }
5792 else
5793 Result += "\t0,\n";
5794
5795 if (ClassProperties.size() > 0) {
5796 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5797 Result += ClassName; Result += "_$_"; Result += CatName;
5798 Result += ",\n";
5799 }
5800 else
5801 Result += "\t0,\n";
5802
5803 Result += "};\n";
5804}
5805
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005806static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5807 ASTContext *Context, std::string &Result,
5808 ArrayRef<ObjCMethodDecl *> Methods,
5809 StringRef VarName,
5810 StringRef ProtocolName) {
5811 if (Methods.size() == 0)
5812 return;
5813
5814 Result += "\nstatic const char *";
5815 Result += VarName; Result += ProtocolName;
5816 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5817 Result += "{\n";
5818 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5819 ObjCMethodDecl *MD = Methods[i];
5820 std::string MethodTypeString, QuoteMethodTypeString;
5821 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5822 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5823 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5824 if (i == e-1)
5825 Result += "\n};\n";
5826 else {
5827 Result += ",\n";
5828 }
5829 }
5830}
5831
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005832static void Write_IvarOffsetVar(ASTContext *Context,
5833 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005834 ArrayRef<ObjCIvarDecl *> Ivars,
5835 StringRef VarName,
5836 StringRef ClassName) {
5837 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5838 // this is what happens:
5839 /**
5840 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5841 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5842 Class->getVisibility() == HiddenVisibility)
5843 Visibility shoud be: HiddenVisibility;
5844 else
5845 Visibility shoud be: DefaultVisibility;
5846 */
5847
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005848 Result += "\n";
5849 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5850 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005851 if (Context->getLangOpts().MicrosoftExt)
5852 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5853
5854 if (!Context->getLangOpts().MicrosoftExt ||
5855 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005856 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005857 Result += "unsigned long int ";
5858 else
5859 Result += "__declspec(dllexport) unsigned long int ";
5860
5861 Result += VarName;
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005862 Result += ClassName; Result += "_";
5863 Result += IvarDecl->getName();
5864 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5865 Result += " = ";
5866 if (IvarDecl->isBitField()) {
5867 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5868 // place all bitfields at offset 0.
5869 Result += "0;\n";
5870 }
5871 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005872 Result += "__OFFSETOFIVAR__(struct ";
5873 Result += ClassName;
5874 Result += "_IMPL, ";
5875 Result += IvarDecl->getName(); Result += ");\n";
5876 }
5877 }
5878}
5879
Fariborz Jahanianae932952012-02-10 20:47:10 +00005880static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5881 ASTContext *Context, std::string &Result,
5882 ArrayRef<ObjCIvarDecl *> Ivars,
5883 StringRef VarName,
5884 StringRef ClassName) {
5885 if (Ivars.size() > 0) {
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005886 Write_IvarOffsetVar(Context, Result, Ivars, "OBJC_IVAR_$_", ClassName);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005887
Fariborz Jahanianae932952012-02-10 20:47:10 +00005888 Result += "\nstatic ";
5889 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5890 Result += " "; Result += VarName;
5891 Result += ClassName;
5892 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5893 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5894 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5895 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5896 ObjCIvarDecl *IvarDecl = Ivars[i];
5897 if (i == 0)
5898 Result += "\t{{";
5899 else
5900 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005901
5902 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5903 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5904 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005905
5906 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5907 std::string IvarTypeString, QuoteIvarTypeString;
5908 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5909 IvarDecl);
5910 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5911 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5912
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005913 // FIXME. this alignment represents the host alignment and need be changed to
5914 // represent the target alignment.
5915 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5916 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005917 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005918 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5919 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005920 if (i == e-1)
5921 Result += "}}\n";
5922 else
5923 Result += "},\n";
5924 }
5925 Result += "};\n";
5926 }
5927}
5928
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005929/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005930void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5931 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005932
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005933 // Do not synthesize the protocol more than once.
5934 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5935 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005936 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005937
5938 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5939 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005940 // Must write out all protocol definitions in current qualifier list,
5941 // and in their nested qualifiers before writing out current definition.
5942 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5943 E = PDecl->protocol_end(); I != E; ++I)
5944 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005945
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005946 // Construct method lists.
5947 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5948 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5949 for (ObjCProtocolDecl::instmeth_iterator
5950 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5951 I != E; ++I) {
5952 ObjCMethodDecl *MD = *I;
5953 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5954 OptInstanceMethods.push_back(MD);
5955 } else {
5956 InstanceMethods.push_back(MD);
5957 }
5958 }
5959
5960 for (ObjCProtocolDecl::classmeth_iterator
5961 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5962 I != E; ++I) {
5963 ObjCMethodDecl *MD = *I;
5964 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5965 OptClassMethods.push_back(MD);
5966 } else {
5967 ClassMethods.push_back(MD);
5968 }
5969 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005970 std::vector<ObjCMethodDecl *> AllMethods;
5971 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5972 AllMethods.push_back(InstanceMethods[i]);
5973 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5974 AllMethods.push_back(ClassMethods[i]);
5975 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5976 AllMethods.push_back(OptInstanceMethods[i]);
5977 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5978 AllMethods.push_back(OptClassMethods[i]);
5979
5980 Write__extendedMethodTypes_initializer(*this, Context, Result,
5981 AllMethods,
5982 "_OBJC_PROTOCOL_METHOD_TYPES_",
5983 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005984 // Protocol's super protocol list
5985 std::vector<ObjCProtocolDecl *> SuperProtocols;
5986 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5987 E = PDecl->protocol_end(); I != E; ++I)
5988 SuperProtocols.push_back(*I);
5989
5990 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5991 "_OBJC_PROTOCOL_REFS_",
5992 PDecl->getNameAsString());
5993
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005994 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005995 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005996 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005997
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005998 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005999 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006000 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006001
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006002 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006003 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006004 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006005
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006006 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006007 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006008 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006009
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006010 // Protocol's property metadata.
6011 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6012 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6013 E = PDecl->prop_end(); I != E; ++I)
6014 ProtocolProperties.push_back(*I);
6015
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006016 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006017 /* Container */0,
6018 "_OBJC_PROTOCOL_PROPERTIES_",
6019 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006020
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006021 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006022 Result += "\n";
6023 if (LangOpts.MicrosoftExt)
6024 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006025 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006026 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006027 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6028 Result += "\t0,\n"; // id is; is null
6029 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006030 if (SuperProtocols.size() > 0) {
6031 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6032 Result += PDecl->getNameAsString(); Result += ",\n";
6033 }
6034 else
6035 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006036 if (InstanceMethods.size() > 0) {
6037 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6038 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006039 }
6040 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006041 Result += "\t0,\n";
6042
6043 if (ClassMethods.size() > 0) {
6044 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6045 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006046 }
6047 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006048 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006049
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006050 if (OptInstanceMethods.size() > 0) {
6051 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6052 Result += PDecl->getNameAsString(); Result += ",\n";
6053 }
6054 else
6055 Result += "\t0,\n";
6056
6057 if (OptClassMethods.size() > 0) {
6058 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6059 Result += PDecl->getNameAsString(); Result += ",\n";
6060 }
6061 else
6062 Result += "\t0,\n";
6063
6064 if (ProtocolProperties.size() > 0) {
6065 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6066 Result += PDecl->getNameAsString(); Result += ",\n";
6067 }
6068 else
6069 Result += "\t0,\n";
6070
6071 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6072 Result += "\t0,\n";
6073
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006074 if (AllMethods.size() > 0) {
6075 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6076 Result += PDecl->getNameAsString();
6077 Result += "\n};\n";
6078 }
6079 else
6080 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006081
6082 // Use this protocol meta-data to build protocol list table in section
6083 // .objc_protolist$B
6084 // Unspecified visibility means 'private extern'.
6085 if (LangOpts.MicrosoftExt)
6086 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6087 Result += "struct _protocol_t *";
6088 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6089 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6090 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006091
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006092 // Mark this protocol as having been generated.
6093 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6094 llvm_unreachable("protocol already synthesized");
6095
6096}
6097
6098void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6099 const ObjCList<ObjCProtocolDecl> &Protocols,
6100 StringRef prefix, StringRef ClassName,
6101 std::string &Result) {
6102 if (Protocols.empty()) return;
6103
6104 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006105 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006106
6107 // Output the top lovel protocol meta-data for the class.
6108 /* struct _objc_protocol_list {
6109 struct _objc_protocol_list *next;
6110 int protocol_count;
6111 struct _objc_protocol *class_protocols[];
6112 }
6113 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006114 Result += "\n";
6115 if (LangOpts.MicrosoftExt)
6116 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6117 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006118 Result += "\tstruct _objc_protocol_list *next;\n";
6119 Result += "\tint protocol_count;\n";
6120 Result += "\tstruct _objc_protocol *class_protocols[";
6121 Result += utostr(Protocols.size());
6122 Result += "];\n} _OBJC_";
6123 Result += prefix;
6124 Result += "_PROTOCOLS_";
6125 Result += ClassName;
6126 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6127 "{\n\t0, ";
6128 Result += utostr(Protocols.size());
6129 Result += "\n";
6130
6131 Result += "\t,{&_OBJC_PROTOCOL_";
6132 Result += Protocols[0]->getNameAsString();
6133 Result += " \n";
6134
6135 for (unsigned i = 1; i != Protocols.size(); i++) {
6136 Result += "\t ,&_OBJC_PROTOCOL_";
6137 Result += Protocols[i]->getNameAsString();
6138 Result += "\n";
6139 }
6140 Result += "\t }\n};\n";
6141}
6142
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006143/// hasObjCExceptionAttribute - Return true if this class or any super
6144/// class has the __objc_exception__ attribute.
6145/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6146static bool hasObjCExceptionAttribute(ASTContext &Context,
6147 const ObjCInterfaceDecl *OID) {
6148 if (OID->hasAttr<ObjCExceptionAttr>())
6149 return true;
6150 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6151 return hasObjCExceptionAttribute(Context, Super);
6152 return false;
6153}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006154
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006155void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6156 std::string &Result) {
6157 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6158
6159 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006160 if (CDecl->isImplicitInterfaceDecl())
6161 assert(false &&
6162 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006163
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006164 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006165 SmallVector<ObjCIvarDecl *, 8> IVars;
6166
6167 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6168 IVD; IVD = IVD->getNextIvar()) {
6169 // Ignore unnamed bit-fields.
6170 if (!IVD->getDeclName())
6171 continue;
6172 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006173 }
6174
Fariborz Jahanianae932952012-02-10 20:47:10 +00006175 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006176 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanianae932952012-02-10 20:47:10 +00006177 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006178
6179 // Build _objc_method_list for class's instance methods if needed
6180 SmallVector<ObjCMethodDecl *, 32>
6181 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6182
6183 // If any of our property implementations have associated getters or
6184 // setters, produce metadata for them as well.
6185 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6186 PropEnd = IDecl->propimpl_end();
6187 Prop != PropEnd; ++Prop) {
6188 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6189 continue;
6190 if (!(*Prop)->getPropertyIvarDecl())
6191 continue;
6192 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6193 if (!PD)
6194 continue;
6195 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6196 if (!Getter->isDefined())
6197 InstanceMethods.push_back(Getter);
6198 if (PD->isReadOnly())
6199 continue;
6200 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6201 if (!Setter->isDefined())
6202 InstanceMethods.push_back(Setter);
6203 }
6204
6205 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6206 "_OBJC_$_INSTANCE_METHODS_",
6207 IDecl->getNameAsString(), true);
6208
6209 SmallVector<ObjCMethodDecl *, 32>
6210 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6211
6212 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6213 "_OBJC_$_CLASS_METHODS_",
6214 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006215
6216 // Protocols referenced in class declaration?
6217 // Protocol's super protocol list
6218 std::vector<ObjCProtocolDecl *> RefedProtocols;
6219 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6220 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6221 E = Protocols.end();
6222 I != E; ++I) {
6223 RefedProtocols.push_back(*I);
6224 // Must write out all protocol definitions in current qualifier list,
6225 // and in their nested qualifiers before writing out current definition.
6226 RewriteObjCProtocolMetaData(*I, Result);
6227 }
6228
6229 Write_protocol_list_initializer(Context, Result,
6230 RefedProtocols,
6231 "_OBJC_CLASS_PROTOCOLS_$_",
6232 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006233
6234 // Protocol's property metadata.
6235 std::vector<ObjCPropertyDecl *> ClassProperties;
6236 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6237 E = CDecl->prop_end(); I != E; ++I)
6238 ClassProperties.push_back(*I);
6239
6240 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6241 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006242 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006243 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006244
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006245
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006246 // Data for initializing _class_ro_t metaclass meta-data
6247 uint32_t flags = CLS_META;
6248 std::string InstanceSize;
6249 std::string InstanceStart;
6250
6251
6252 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6253 if (classIsHidden)
6254 flags |= OBJC2_CLS_HIDDEN;
6255
6256 if (!CDecl->getSuperClass())
6257 // class is root
6258 flags |= CLS_ROOT;
6259 InstanceSize = "sizeof(struct _class_t)";
6260 InstanceStart = InstanceSize;
6261 Write__class_ro_t_initializer(Context, Result, flags,
6262 InstanceStart, InstanceSize,
6263 ClassMethods,
6264 0,
6265 0,
6266 0,
6267 "_OBJC_METACLASS_RO_$_",
6268 CDecl->getNameAsString());
6269
6270
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006271 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006272 flags = CLS;
6273 if (classIsHidden)
6274 flags |= OBJC2_CLS_HIDDEN;
6275
6276 if (hasObjCExceptionAttribute(*Context, CDecl))
6277 flags |= CLS_EXCEPTION;
6278
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006279 if (!CDecl->getSuperClass())
6280 // class is root
6281 flags |= CLS_ROOT;
6282
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006283 InstanceSize.clear();
6284 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006285 if (!ObjCSynthesizedStructs.count(CDecl)) {
6286 InstanceSize = "0";
6287 InstanceStart = "0";
6288 }
6289 else {
6290 InstanceSize = "sizeof(struct ";
6291 InstanceSize += CDecl->getNameAsString();
6292 InstanceSize += "_IMPL)";
6293
6294 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6295 if (IVD) {
6296 InstanceStart += "__OFFSETOFIVAR__(struct ";
6297 InstanceStart += CDecl->getNameAsString();
6298 InstanceStart += "_IMPL, ";
6299 InstanceStart += IVD->getNameAsString();
6300 InstanceStart += ")";
6301 }
6302 else
6303 InstanceStart = InstanceSize;
6304 }
6305 Write__class_ro_t_initializer(Context, Result, flags,
6306 InstanceStart, InstanceSize,
6307 InstanceMethods,
6308 RefedProtocols,
6309 IVars,
6310 ClassProperties,
6311 "_OBJC_CLASS_RO_$_",
6312 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006313
6314 Write_class_t(Context, Result,
6315 "OBJC_METACLASS_$_",
6316 CDecl, /*metaclass*/true);
6317
6318 Write_class_t(Context, Result,
6319 "OBJC_CLASS_$_",
6320 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006321
6322 if (ImplementationIsNonLazy(IDecl))
6323 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006324
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006325}
6326
6327void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6328 int ClsDefCount = ClassImplementation.size();
6329 int CatDefCount = CategoryImplementation.size();
6330
6331 // For each implemented class, write out all its meta data.
6332 for (int i = 0; i < ClsDefCount; i++)
6333 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6334
6335 // For each implemented category, write out all its meta data.
6336 for (int i = 0; i < CatDefCount; i++)
6337 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6338
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006339 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006340 if (LangOpts.MicrosoftExt)
6341 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006342 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6343 Result += llvm::utostr(ClsDefCount); Result += "]";
6344 Result +=
6345 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6346 "regular,no_dead_strip\")))= {\n";
6347 for (int i = 0; i < ClsDefCount; i++) {
6348 Result += "\t&OBJC_CLASS_$_";
6349 Result += ClassImplementation[i]->getNameAsString();
6350 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006351 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006352 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006353
6354 if (!DefinedNonLazyClasses.empty()) {
6355 if (LangOpts.MicrosoftExt)
6356 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6357 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6358 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6359 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6360 Result += ",\n";
6361 }
6362 Result += "};\n";
6363 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006364 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006365
6366 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006367 if (LangOpts.MicrosoftExt)
6368 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006369 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6370 Result += llvm::utostr(CatDefCount); Result += "]";
6371 Result +=
6372 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6373 "regular,no_dead_strip\")))= {\n";
6374 for (int i = 0; i < CatDefCount; i++) {
6375 Result += "\t&_OBJC_$_CATEGORY_";
6376 Result +=
6377 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6378 Result += "_$_";
6379 Result += CategoryImplementation[i]->getNameAsString();
6380 Result += ",\n";
6381 }
6382 Result += "};\n";
6383 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006384
6385 if (!DefinedNonLazyCategories.empty()) {
6386 if (LangOpts.MicrosoftExt)
6387 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6388 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6389 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6390 Result += "\t&_OBJC_$_CATEGORY_";
6391 Result +=
6392 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6393 Result += "_$_";
6394 Result += DefinedNonLazyCategories[i]->getNameAsString();
6395 Result += ",\n";
6396 }
6397 Result += "};\n";
6398 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006399}
6400
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006401void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6402 if (LangOpts.MicrosoftExt)
6403 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6404
6405 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6406 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006407 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006408}
6409
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006410/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6411/// implementation.
6412void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6413 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006414 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006415 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6416 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006417 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006418 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6419 CDecl = CDecl->getNextClassCategory())
6420 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6421 break;
6422
6423 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006424 FullCategoryName += "_$_";
6425 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006426
6427 // Build _objc_method_list for class's instance methods if needed
6428 SmallVector<ObjCMethodDecl *, 32>
6429 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6430
6431 // If any of our property implementations have associated getters or
6432 // setters, produce metadata for them as well.
6433 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6434 PropEnd = IDecl->propimpl_end();
6435 Prop != PropEnd; ++Prop) {
6436 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6437 continue;
6438 if (!(*Prop)->getPropertyIvarDecl())
6439 continue;
6440 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6441 if (!PD)
6442 continue;
6443 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6444 InstanceMethods.push_back(Getter);
6445 if (PD->isReadOnly())
6446 continue;
6447 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6448 InstanceMethods.push_back(Setter);
6449 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006450
Fariborz Jahanian61186122012-02-17 18:40:41 +00006451 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6452 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6453 FullCategoryName, true);
6454
6455 SmallVector<ObjCMethodDecl *, 32>
6456 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6457
6458 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6459 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6460 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006461
6462 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006463 // Protocol's super protocol list
6464 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006465 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6466 E = CDecl->protocol_end();
6467
6468 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006469 RefedProtocols.push_back(*I);
6470 // Must write out all protocol definitions in current qualifier list,
6471 // and in their nested qualifiers before writing out current definition.
6472 RewriteObjCProtocolMetaData(*I, Result);
6473 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006474
Fariborz Jahanian61186122012-02-17 18:40:41 +00006475 Write_protocol_list_initializer(Context, Result,
6476 RefedProtocols,
6477 "_OBJC_CATEGORY_PROTOCOLS_$_",
6478 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006479
Fariborz Jahanian61186122012-02-17 18:40:41 +00006480 // Protocol's property metadata.
6481 std::vector<ObjCPropertyDecl *> ClassProperties;
6482 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6483 E = CDecl->prop_end(); I != E; ++I)
6484 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006485
Fariborz Jahanian61186122012-02-17 18:40:41 +00006486 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6487 /* Container */0,
6488 "_OBJC_$_PROP_LIST_",
6489 FullCategoryName);
6490
6491 Write_category_t(*this, Context, Result,
6492 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006493 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006494 InstanceMethods,
6495 ClassMethods,
6496 RefedProtocols,
6497 ClassProperties);
6498
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006499 // Determine if this category is also "non-lazy".
6500 if (ImplementationIsNonLazy(IDecl))
6501 DefinedNonLazyCategories.push_back(CDecl);
6502
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006503}
6504
6505// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6506/// class methods.
6507template<typename MethodIterator>
6508void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6509 MethodIterator MethodEnd,
6510 bool IsInstanceMethod,
6511 StringRef prefix,
6512 StringRef ClassName,
6513 std::string &Result) {
6514 if (MethodBegin == MethodEnd) return;
6515
6516 if (!objc_impl_method) {
6517 /* struct _objc_method {
6518 SEL _cmd;
6519 char *method_types;
6520 void *_imp;
6521 }
6522 */
6523 Result += "\nstruct _objc_method {\n";
6524 Result += "\tSEL _cmd;\n";
6525 Result += "\tchar *method_types;\n";
6526 Result += "\tvoid *_imp;\n";
6527 Result += "};\n";
6528
6529 objc_impl_method = true;
6530 }
6531
6532 // Build _objc_method_list for class's methods if needed
6533
6534 /* struct {
6535 struct _objc_method_list *next_method;
6536 int method_count;
6537 struct _objc_method method_list[];
6538 }
6539 */
6540 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006541 Result += "\n";
6542 if (LangOpts.MicrosoftExt) {
6543 if (IsInstanceMethod)
6544 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6545 else
6546 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6547 }
6548 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006549 Result += "\tstruct _objc_method_list *next_method;\n";
6550 Result += "\tint method_count;\n";
6551 Result += "\tstruct _objc_method method_list[";
6552 Result += utostr(NumMethods);
6553 Result += "];\n} _OBJC_";
6554 Result += prefix;
6555 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6556 Result += "_METHODS_";
6557 Result += ClassName;
6558 Result += " __attribute__ ((used, section (\"__OBJC, __";
6559 Result += IsInstanceMethod ? "inst" : "cls";
6560 Result += "_meth\")))= ";
6561 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6562
6563 Result += "\t,{{(SEL)\"";
6564 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6565 std::string MethodTypeString;
6566 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6567 Result += "\", \"";
6568 Result += MethodTypeString;
6569 Result += "\", (void *)";
6570 Result += MethodInternalNames[*MethodBegin];
6571 Result += "}\n";
6572 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6573 Result += "\t ,{(SEL)\"";
6574 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6575 std::string MethodTypeString;
6576 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6577 Result += "\", \"";
6578 Result += MethodTypeString;
6579 Result += "\", (void *)";
6580 Result += MethodInternalNames[*MethodBegin];
6581 Result += "}\n";
6582 }
6583 Result += "\t }\n};\n";
6584}
6585
6586Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6587 SourceRange OldRange = IV->getSourceRange();
6588 Expr *BaseExpr = IV->getBase();
6589
6590 // Rewrite the base, but without actually doing replaces.
6591 {
6592 DisableReplaceStmtScope S(*this);
6593 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6594 IV->setBase(BaseExpr);
6595 }
6596
6597 ObjCIvarDecl *D = IV->getDecl();
6598
6599 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006600
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006601 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6602 const ObjCInterfaceType *iFaceDecl =
6603 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6604 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6605 // lookup which class implements the instance variable.
6606 ObjCInterfaceDecl *clsDeclared = 0;
6607 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6608 clsDeclared);
6609 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6610
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006611 // Build name of symbol holding ivar offset.
6612 std::string IvarOffsetName = "OBJC_IVAR_$_";
6613 IvarOffsetName += clsDeclared->getIdentifier()->getName();
6614 IvarOffsetName += "_";
6615 IvarOffsetName += D->getName();
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006616 ReferencedIvars[clsDeclared].insert(D);
6617
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006618 // cast offset to "char *".
6619 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6620 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006621 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006622 BaseExpr);
6623 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6624 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6625 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006626 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6627 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006628 SourceLocation());
6629 BinaryOperator *addExpr =
6630 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6631 Context->getPointerType(Context->CharTy),
6632 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006633 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006634 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6635 SourceLocation(),
6636 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006637 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006638 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006639 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006640
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006641 castExpr = NoTypeInfoCStyleCastExpr(Context,
6642 castT,
6643 CK_BitCast,
6644 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006645 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006646 VK_LValue, OK_Ordinary,
6647 SourceLocation());
6648 PE = new (Context) ParenExpr(OldRange.getBegin(),
6649 OldRange.getEnd(),
6650 Exp);
6651
6652 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006653 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006654
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006655 ReplaceStmtWithRange(IV, Replacement, OldRange);
6656 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006657}
6658