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