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