1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
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 // This coordinates the per-module state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGDebugInfo.h"
15 #include "CodeGenModule.h"
16 #include "CodeGenFunction.h"
17 #include "CGCall.h"
18 #include "CGObjCRuntime.h"
19 #include "Mangle.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Module.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Target/TargetData.h"
30 using namespace clang;
31 using namespace CodeGen;
32 
33 
34 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
35                              llvm::Module &M, const llvm::TargetData &TD,
36                              Diagnostic &diags, bool GenerateDebugInfo)
37   : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
38     Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
39     CFConstantStringClassRef(0), NSConcreteGlobalBlock(0),
40     BlockDescriptorType(0), GenericBlockLiteralType(0) {
41 
42   if (Features.ObjC1) {
43     if (Features.NeXTRuntime) {
44       Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
45                                        : CreateMacObjCRuntime(*this);
46     } else {
47       Runtime = CreateGNUObjCRuntime(*this);
48     }
49   }
50 
51   // If debug info generation is enabled, create the CGDebugInfo object.
52   DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
53 
54   Block.GlobalUniqueCount = 0;
55 }
56 
57 CodeGenModule::~CodeGenModule() {
58   delete Runtime;
59   delete DebugInfo;
60 }
61 
62 void CodeGenModule::Release() {
63   EmitDeferred();
64   EmitAliases();
65   if (Runtime)
66     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
67       AddGlobalCtor(ObjCInitFunction);
68   EmitCtorList(GlobalCtors, "llvm.global_ctors");
69   EmitCtorList(GlobalDtors, "llvm.global_dtors");
70   EmitAnnotations();
71   EmitLLVMUsed();
72   BindRuntimeFunctions();
73 }
74 
75 void CodeGenModule::BindRuntimeFunctions() {
76   // Deal with protecting runtime function names.
77   for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
78     llvm::Function *Fn = RuntimeFunctions[i].first;
79     const std::string &Name = RuntimeFunctions[i].second;
80 
81     // Discard unused runtime functions.
82     if (Fn->use_empty()) {
83       Fn->eraseFromParent();
84       continue;
85     }
86 
87     // See if there is a conflict against a function.
88     llvm::Function *Conflict = TheModule.getFunction(Name);
89     if (Conflict) {
90       // Decide which version to take. If the conflict is a definition
91       // we are forced to take that, otherwise assume the runtime
92       // knows best.
93       if (!Conflict->isDeclaration()) {
94         llvm::Value *Casted =
95           llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
96         Fn->replaceAllUsesWith(Casted);
97         Fn->eraseFromParent();
98       } else {
99         Fn->takeName(Conflict);
100         llvm::Value *Casted =
101           llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
102         Conflict->replaceAllUsesWith(Casted);
103         Conflict->eraseFromParent();
104       }
105     } else {
106       // FIXME: There still may be conflicts with aliases and
107       // variables.
108       Fn->setName(Name);
109     }
110   }
111 }
112 
113 /// ErrorUnsupported - Print out an error that codegen doesn't support the
114 /// specified stmt yet.
115 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
116                                      bool OmitOnError) {
117   if (OmitOnError && getDiags().hasErrorOccurred())
118     return;
119   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
120                                                "cannot compile this %0 yet");
121   std::string Msg = Type;
122   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
123     << Msg << S->getSourceRange();
124 }
125 
126 /// ErrorUnsupported - Print out an error that codegen doesn't support the
127 /// specified decl yet.
128 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
129                                      bool OmitOnError) {
130   if (OmitOnError && getDiags().hasErrorOccurred())
131     return;
132   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
133                                                "cannot compile this %0 yet");
134   std::string Msg = Type;
135   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
136 }
137 
138 /// setGlobalVisibility - Set the visibility for the given LLVM
139 /// GlobalValue according to the given clang AST visibility value.
140 static void setGlobalVisibility(llvm::GlobalValue *GV,
141                                 VisibilityAttr::VisibilityTypes Vis) {
142   switch (Vis) {
143   default: assert(0 && "Unknown visibility!");
144   case VisibilityAttr::DefaultVisibility:
145     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
146     break;
147   case VisibilityAttr::HiddenVisibility:
148     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
149     break;
150   case VisibilityAttr::ProtectedVisibility:
151     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
152     break;
153   }
154 }
155 
156 /// \brief Retrieves the mangled name for the given declaration.
157 ///
158 /// If the given declaration requires a mangled name, returns an
159 /// IdentifierInfo* containing the mangled name. Otherwise, returns
160 /// the name of the declaration as an identifier.
161 ///
162 /// FIXME: Returning an IdentifierInfo* here is a total hack. We
163 /// really need some kind of string abstraction that either stores a
164 /// mangled name or stores an IdentifierInfo*. This will require
165 /// changes to the GlobalDeclMap, too.
166 ///
167 /// FIXME: Performance here is going to be terribly until we start
168 /// caching mangled names. However, we should fix the problem above
169 /// first.
170 IdentifierInfo *CodeGenModule::getMangledName(const NamedDecl *ND) const {
171   std::string Name;
172   llvm::raw_string_ostream Out(Name);
173   if (!mangleName(ND, Context, Out))
174     return ND->getIdentifier();
175 
176   return &Context.Idents.get(Out.str());
177 }
178 
179 /// AddGlobalCtor - Add a function to the list that will be called before
180 /// main() runs.
181 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
182   // FIXME: Type coercion of void()* types.
183   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
184 }
185 
186 /// AddGlobalDtor - Add a function to the list that will be called
187 /// when the module is unloaded.
188 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
189   // FIXME: Type coercion of void()* types.
190   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
191 }
192 
193 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
194   // Ctor function type is void()*.
195   llvm::FunctionType* CtorFTy =
196     llvm::FunctionType::get(llvm::Type::VoidTy,
197                             std::vector<const llvm::Type*>(),
198                             false);
199   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
200 
201   // Get the type of a ctor entry, { i32, void ()* }.
202   llvm::StructType* CtorStructTy =
203     llvm::StructType::get(llvm::Type::Int32Ty,
204                           llvm::PointerType::getUnqual(CtorFTy), NULL);
205 
206   // Construct the constructor and destructor arrays.
207   std::vector<llvm::Constant*> Ctors;
208   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
209     std::vector<llvm::Constant*> S;
210     S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
211     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
212     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
213   }
214 
215   if (!Ctors.empty()) {
216     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
217     new llvm::GlobalVariable(AT, false,
218                              llvm::GlobalValue::AppendingLinkage,
219                              llvm::ConstantArray::get(AT, Ctors),
220                              GlobalName,
221                              &TheModule);
222   }
223 }
224 
225 void CodeGenModule::EmitAnnotations() {
226   if (Annotations.empty())
227     return;
228 
229   // Create a new global variable for the ConstantStruct in the Module.
230   llvm::Constant *Array =
231   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
232                                                 Annotations.size()),
233                            Annotations);
234   llvm::GlobalValue *gv =
235   new llvm::GlobalVariable(Array->getType(), false,
236                            llvm::GlobalValue::AppendingLinkage, Array,
237                            "llvm.global.annotations", &TheModule);
238   gv->setSection("llvm.metadata");
239 }
240 
241 void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
242                                              bool IsInternal,
243                                              bool IsInline,
244                                              llvm::GlobalValue *GV,
245                                              bool ForDefinition) {
246   // FIXME: Set up linkage and many other things.  Note, this is a simple
247   // approximation of what we really want.
248   if (!ForDefinition) {
249     // Only a few attributes are set on declarations.
250     if (D->getAttr<DLLImportAttr>()) {
251       // The dllimport attribute is overridden by a subsequent declaration as
252       // dllexport.
253       if (!D->getAttr<DLLExportAttr>()) {
254         // dllimport attribute can be applied only to function decls, not to
255         // definitions.
256         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
257           if (!FD->getBody())
258             GV->setLinkage(llvm::Function::DLLImportLinkage);
259         } else
260           GV->setLinkage(llvm::Function::DLLImportLinkage);
261       }
262     }
263   } else {
264     if (IsInternal) {
265       GV->setLinkage(llvm::Function::InternalLinkage);
266     } else {
267       if (D->getAttr<DLLExportAttr>()) {
268         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
269           // The dllexport attribute is ignored for undefined symbols.
270           if (FD->getBody())
271             GV->setLinkage(llvm::Function::DLLExportLinkage);
272         } else
273           GV->setLinkage(llvm::Function::DLLExportLinkage);
274       } else if (D->getAttr<WeakAttr>() || IsInline)
275         GV->setLinkage(llvm::Function::WeakLinkage);
276     }
277   }
278 
279   // FIXME: Figure out the relative priority of the attribute,
280   // -fvisibility, and private_extern.
281   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
282     setGlobalVisibility(GV, attr->getVisibility());
283   // FIXME: else handle -fvisibility
284 
285   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
286     // Prefaced with special LLVM marker to indicate that the name
287     // should not be munged.
288     GV->setName("\01" + ALA->getLabel());
289   }
290 
291   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
292     GV->setSection(SA->getName());
293 
294   // Only add to llvm.used when we see a definition, otherwise we
295   // might add multiple times or risk the value being replaced by a
296   // subsequent RAUW.
297   if (ForDefinition) {
298     if (D->getAttr<UsedAttr>())
299       AddUsedGlobal(GV);
300   }
301 }
302 
303 void CodeGenModule::SetFunctionAttributes(const Decl *D,
304                                           const CGFunctionInfo &Info,
305                                           llvm::Function *F) {
306   AttributeListType AttributeList;
307   ConstructAttributeList(Info, D, AttributeList);
308 
309   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
310                                         AttributeList.size()));
311 
312   // Set the appropriate calling convention for the Function.
313   if (D->getAttr<FastCallAttr>())
314     F->setCallingConv(llvm::CallingConv::X86_FastCall);
315 
316   if (D->getAttr<StdCallAttr>())
317     F->setCallingConv(llvm::CallingConv::X86_StdCall);
318 }
319 
320 /// SetFunctionAttributesForDefinition - Set function attributes
321 /// specific to a function definition.
322 void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
323                                                        llvm::Function *F) {
324   if (isa<ObjCMethodDecl>(D)) {
325     SetGlobalValueAttributes(D, true, false, F, true);
326   } else {
327     const FunctionDecl *FD = cast<FunctionDecl>(D);
328     SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
329                              FD->isInline(), F, true);
330   }
331 
332   if (!Features.Exceptions)
333     F->addFnAttr(llvm::Attribute::NoUnwind);
334 
335   if (D->getAttr<AlwaysInlineAttr>())
336     F->addFnAttr(llvm::Attribute::AlwaysInline);
337 }
338 
339 void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
340                                         llvm::Function *F) {
341   SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
342 
343   SetFunctionAttributesForDefinition(MD, F);
344 }
345 
346 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
347                                           llvm::Function *F) {
348   SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
349 
350   SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
351                            FD->isInline(), F, false);
352 }
353 
354 
355 void CodeGenModule::EmitAliases() {
356   for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
357     const FunctionDecl *D = Aliases[i];
358     const AliasAttr *AA = D->getAttr<AliasAttr>();
359 
360     // This is something of a hack, if the FunctionDecl got overridden
361     // then its attributes will be moved to the new declaration. In
362     // this case the current decl has no alias attribute, but we will
363     // eventually see it.
364     if (!AA)
365       continue;
366 
367     const std::string& aliaseeName = AA->getAliasee();
368     llvm::Function *aliasee = getModule().getFunction(aliaseeName);
369     if (!aliasee) {
370       // FIXME: This isn't unsupported, this is just an error, which
371       // sema should catch, but...
372       ErrorUnsupported(D, "alias referencing a missing function");
373       continue;
374     }
375 
376     llvm::GlobalValue *GA =
377       new llvm::GlobalAlias(aliasee->getType(),
378                             llvm::Function::ExternalLinkage,
379                             getMangledName(D)->getName(), aliasee,
380                             &getModule());
381 
382     llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
383     if (Entry) {
384       // If we created a dummy function for this then replace it.
385       GA->takeName(Entry);
386 
387       llvm::Value *Casted =
388         llvm::ConstantExpr::getBitCast(GA, Entry->getType());
389       Entry->replaceAllUsesWith(Casted);
390       Entry->eraseFromParent();
391 
392       Entry = GA;
393     }
394 
395     // Alias should never be internal or inline.
396     SetGlobalValueAttributes(D, false, false, GA, true);
397   }
398 }
399 
400 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
401   assert(!GV->isDeclaration() &&
402          "Only globals with definition can force usage.");
403   llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
404   LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
405 }
406 
407 void CodeGenModule::EmitLLVMUsed() {
408   // Don't create llvm.used if there is no need.
409   if (LLVMUsed.empty())
410     return;
411 
412   llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
413                                               LLVMUsed.size());
414   llvm::GlobalVariable *GV =
415     new llvm::GlobalVariable(ATy, false,
416                              llvm::GlobalValue::AppendingLinkage,
417                              llvm::ConstantArray::get(ATy, LLVMUsed),
418                              "llvm.used", &getModule());
419 
420   GV->setSection("llvm.metadata");
421 }
422 
423 void CodeGenModule::EmitDeferred() {
424   // Emit code for any deferred decl which was used.  Since a
425   // previously unused static decl may become used during the
426   // generation of code for a static function, iterate until no
427   // changes are made.
428   bool Changed;
429   do {
430     Changed = false;
431 
432     for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
433          e = DeferredDecls.end(); i != e; ) {
434       const ValueDecl *D = *i;
435 
436       // Check if we have used a decl with the same name
437       // FIXME: The AST should have some sort of aggregate decls or
438       // global symbol map.
439       // FIXME: This is missing some important cases. For example, we
440       // need to check for uses in an alias.
441       if (!GlobalDeclMap.count(getMangledName(D))) {
442         i++;
443         continue;
444       }
445 
446       // Emit the definition.
447       EmitGlobalDefinition(D);
448 
449       // Erase the used decl from the list.
450       i = DeferredDecls.erase(i);
451 
452       // Remember that we made a change.
453       Changed = true;
454     }
455   } while (Changed);
456 }
457 
458 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
459 /// annotation information for a given GlobalValue.  The annotation struct is
460 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
461 /// GlobalValue being annotated.  The second field is the constant string
462 /// created from the AnnotateAttr's annotation.  The third field is a constant
463 /// string containing the name of the translation unit.  The fourth field is
464 /// the line number in the file of the annotated value declaration.
465 ///
466 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
467 ///        appears to.
468 ///
469 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
470                                                 const AnnotateAttr *AA,
471                                                 unsigned LineNo) {
472   llvm::Module *M = &getModule();
473 
474   // get [N x i8] constants for the annotation string, and the filename string
475   // which are the 2nd and 3rd elements of the global annotation structure.
476   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
477   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
478   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
479                                                   true);
480 
481   // Get the two global values corresponding to the ConstantArrays we just
482   // created to hold the bytes of the strings.
483   llvm::GlobalValue *annoGV =
484   new llvm::GlobalVariable(anno->getType(), false,
485                            llvm::GlobalValue::InternalLinkage, anno,
486                            GV->getName() + ".str", M);
487   // translation unit name string, emitted into the llvm.metadata section.
488   llvm::GlobalValue *unitGV =
489   new llvm::GlobalVariable(unit->getType(), false,
490                            llvm::GlobalValue::InternalLinkage, unit, ".str", M);
491 
492   // Create the ConstantStruct that is the global annotion.
493   llvm::Constant *Fields[4] = {
494     llvm::ConstantExpr::getBitCast(GV, SBP),
495     llvm::ConstantExpr::getBitCast(annoGV, SBP),
496     llvm::ConstantExpr::getBitCast(unitGV, SBP),
497     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
498   };
499   return llvm::ConstantStruct::get(Fields, 4, false);
500 }
501 
502 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
503   // Never defer when EmitAllDecls is specified or the decl has
504   // attribute used.
505   if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
506     return false;
507 
508   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
509     // Constructors and destructors should never be deferred.
510     if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
511       return false;
512 
513     if (FD->getStorageClass() != FunctionDecl::Static)
514       return false;
515   } else {
516     const VarDecl *VD = cast<VarDecl>(Global);
517     assert(VD->isFileVarDecl() && "Invalid decl.");
518 
519     if (VD->getStorageClass() != VarDecl::Static)
520       return false;
521   }
522 
523   return true;
524 }
525 
526 void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
527   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
528     // Aliases are deferred until code for everything else has been
529     // emitted.
530     if (FD->getAttr<AliasAttr>()) {
531       assert(!FD->isThisDeclarationADefinition() &&
532              "Function alias cannot have a definition!");
533       Aliases.push_back(FD);
534       return;
535     }
536 
537     // Forward declarations are emitted lazily on first use.
538     if (!FD->isThisDeclarationADefinition())
539       return;
540   } else {
541     const VarDecl *VD = cast<VarDecl>(Global);
542     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
543 
544     // Forward declarations are emitted lazily on first use.
545     if ((VD->getStorageClass() == VarDecl::Extern ||
546          VD->getStorageClass() == VarDecl::PrivateExtern) &&
547         VD->getInit() == 0)
548       return;
549   }
550 
551   // Defer code generation when possible.
552   if (MayDeferGeneration(Global)) {
553     DeferredDecls.push_back(Global);
554     return;
555   }
556 
557   // Otherwise emit the definition.
558   EmitGlobalDefinition(Global);
559 }
560 
561 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
562   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
563     EmitGlobalFunctionDefinition(FD);
564   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
565     EmitGlobalVarDefinition(VD);
566   } else {
567     assert(0 && "Invalid argument to EmitGlobalDefinition()");
568   }
569 }
570 
571  llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
572   assert(D->hasGlobalStorage() && "Not a global variable");
573 
574   QualType ASTTy = D->getType();
575   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
576   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
577 
578   // Lookup the entry, lazily creating it if necessary.
579   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
580   if (!Entry) {
581     llvm::GlobalVariable *GV =
582       new llvm::GlobalVariable(Ty, false,
583                                llvm::GlobalValue::ExternalLinkage,
584                                0, getMangledName(D)->getName(), &getModule(),
585                                0, ASTTy.getAddressSpace());
586     Entry = GV;
587 
588     // Handle things which are present even on external declarations.
589 
590     // FIXME: This code is overly simple and should be merged with
591     // other global handling.
592 
593     GV->setConstant(D->getType().isConstant(Context));
594 
595     if (D->getStorageClass() == VarDecl::PrivateExtern)
596       setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
597   }
598 
599   // Make sure the result is of the correct type.
600   return llvm::ConstantExpr::getBitCast(Entry, PTy);
601 }
602 
603 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
604   llvm::Constant *Init = 0;
605   QualType ASTTy = D->getType();
606   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
607 
608   if (D->getInit() == 0) {
609     // This is a tentative definition; tentative definitions are
610     // implicitly initialized with { 0 }
611     const llvm::Type* InitTy;
612     if (ASTTy->isIncompleteArrayType()) {
613       // An incomplete array is normally [ TYPE x 0 ], but we need
614       // to fix it to [ TYPE x 1 ].
615       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
616       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
617     } else {
618       InitTy = VarTy;
619     }
620     Init = llvm::Constant::getNullValue(InitTy);
621   } else {
622     Init = EmitConstantExpr(D->getInit());
623   }
624   const llvm::Type* InitType = Init->getType();
625 
626   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
627   llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
628 
629   if (!GV) {
630     GV = new llvm::GlobalVariable(InitType, false,
631                                   llvm::GlobalValue::ExternalLinkage,
632                                   0, getMangledName(D)->getName(),
633                                   &getModule(), 0, ASTTy.getAddressSpace());
634   } else if (GV->getType() !=
635              llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
636     // We have a definition after a prototype with the wrong type.
637     // We must make a new GlobalVariable* and update everything that used OldGV
638     // (a declaration or tentative definition) with the new GlobalVariable*
639     // (which will be a definition).
640     //
641     // This happens if there is a prototype for a global (e.g. "extern int x[];")
642     // and then a definition of a different type (e.g. "int x[10];"). This also
643     // happens when an initializer has a different type from the type of the
644     // global (this happens with unions).
645     //
646     // FIXME: This also ends up happening if there's a definition followed by
647     // a tentative definition!  (Although Sema rejects that construct
648     // at the moment.)
649 
650     // Save the old global
651     llvm::GlobalVariable *OldGV = GV;
652 
653     // Make a new global with the correct type
654     GV = new llvm::GlobalVariable(InitType, false,
655                                   llvm::GlobalValue::ExternalLinkage,
656                                   0, getMangledName(D)->getName(),
657                                   &getModule(), 0, ASTTy.getAddressSpace());
658     // Steal the name of the old global
659     GV->takeName(OldGV);
660 
661     // Replace all uses of the old global with the new global
662     llvm::Constant *NewPtrForOldDecl =
663         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
664     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
665 
666     // Erase the old global, since it is no longer used.
667     OldGV->eraseFromParent();
668   }
669 
670   Entry = GV;
671 
672   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
673     SourceManager &SM = Context.getSourceManager();
674     AddAnnotation(EmitAnnotateAttr(GV, AA,
675                               SM.getInstantiationLineNumber(D->getLocation())));
676   }
677 
678   GV->setInitializer(Init);
679   GV->setConstant(D->getType().isConstant(Context));
680 
681   // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
682   unsigned Align;
683   if (const IncompleteArrayType* IAT =
684         Context.getAsIncompleteArrayType(D->getType()))
685     Align = Context.getTypeAlign(IAT->getElementType());
686   else
687     Align = Context.getTypeAlign(D->getType());
688   if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
689     Align = std::max(Align, AA->getAlignment());
690   }
691   GV->setAlignment(Align / 8);
692 
693   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
694     setGlobalVisibility(GV, attr->getVisibility());
695   // FIXME: else handle -fvisibility
696 
697   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
698     // Prefaced with special LLVM marker to indicate that the name
699     // should not be munged.
700     GV->setName("\01" + ALA->getLabel());
701   }
702 
703   // Set the llvm linkage type as appropriate.
704   if (D->getStorageClass() == VarDecl::Static)
705     GV->setLinkage(llvm::Function::InternalLinkage);
706   else if (D->getAttr<DLLImportAttr>())
707     GV->setLinkage(llvm::Function::DLLImportLinkage);
708   else if (D->getAttr<DLLExportAttr>())
709     GV->setLinkage(llvm::Function::DLLExportLinkage);
710   else if (D->getAttr<WeakAttr>())
711     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
712   else {
713     // FIXME: This isn't right.  This should handle common linkage and other
714     // stuff.
715     switch (D->getStorageClass()) {
716     case VarDecl::Static: assert(0 && "This case handled above");
717     case VarDecl::Auto:
718     case VarDecl::Register:
719       assert(0 && "Can't have auto or register globals");
720     case VarDecl::None:
721       if (!D->getInit())
722         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
723       else
724         GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
725       break;
726     case VarDecl::Extern:
727       // FIXME: common
728       break;
729 
730     case VarDecl::PrivateExtern:
731       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
732       // FIXME: common
733       break;
734     }
735   }
736 
737   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
738     GV->setSection(SA->getName());
739 
740   if (D->getAttr<UsedAttr>())
741     AddUsedGlobal(GV);
742 
743   // Emit global variable debug information.
744   CGDebugInfo *DI = getDebugInfo();
745   if(DI) {
746     DI->setLocation(D->getLocation());
747     DI->EmitGlobalVariable(GV, D);
748   }
749 }
750 
751 llvm::GlobalValue *
752 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
753   const llvm::Type *Ty = getTypes().ConvertType(D->getType());
754   llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
755                                              llvm::Function::ExternalLinkage,
756                                              getMangledName(D)->getName(),
757                                              &getModule());
758   SetFunctionAttributes(D, F);
759   return F;
760 }
761 
762 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
763   QualType ASTTy = D->getType();
764   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
765   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
766 
767   // Lookup the entry, lazily creating it if necessary.
768   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
769   if (!Entry)
770     Entry = EmitForwardFunctionDefinition(D);
771 
772   return llvm::ConstantExpr::getBitCast(Entry, PTy);
773 }
774 
775 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
776   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
777   if (!Entry) {
778     Entry = EmitForwardFunctionDefinition(D);
779   } else {
780     // If the types mismatch then we have to rewrite the definition.
781     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
782     if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
783       // Otherwise, we have a definition after a prototype with the wrong type.
784       // F is the Function* for the one with the wrong type, we must make a new
785       // Function* and update everything that used F (a declaration) with the new
786       // Function* (which will be a definition).
787       //
788       // This happens if there is a prototype for a function (e.g. "int f()") and
789       // then a definition of a different type (e.g. "int f(int x)").  Start by
790       // making a new function of the correct type, RAUW, then steal the name.
791       llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
792       NewFn->takeName(Entry);
793 
794       // Replace uses of F with the Function we will endow with a body.
795       llvm::Constant *NewPtrForOldDecl =
796         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
797       Entry->replaceAllUsesWith(NewPtrForOldDecl);
798 
799       // Ok, delete the old function now, which is dead.
800       assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
801       Entry->eraseFromParent();
802 
803       Entry = NewFn;
804     }
805   }
806 
807   llvm::Function *Fn = cast<llvm::Function>(Entry);
808   CodeGenFunction(*this).GenerateCode(D, Fn);
809 
810   SetFunctionAttributesForDefinition(D, Fn);
811 
812   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
813     AddGlobalCtor(Fn, CA->getPriority());
814   } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
815     AddGlobalDtor(Fn, DA->getPriority());
816   }
817 }
818 
819 llvm::Function *
820 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
821                                      const std::string &Name) {
822   llvm::Function *Fn = llvm::Function::Create(FTy,
823                                               llvm::Function::ExternalLinkage,
824                                               "", &TheModule);
825   RuntimeFunctions.push_back(std::make_pair(Fn, Name));
826   return Fn;
827 }
828 
829 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
830   // Make sure that this type is translated.
831   Types.UpdateCompletedType(TD);
832 }
833 
834 
835 /// getBuiltinLibFunction
836 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
837   if (BuiltinID > BuiltinFunctions.size())
838     BuiltinFunctions.resize(BuiltinID);
839 
840   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
841   // a slot for it.
842   assert(BuiltinID && "Invalid Builtin ID");
843   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
844   if (FunctionSlot)
845     return FunctionSlot;
846 
847   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
848 
849   // Get the name, skip over the __builtin_ prefix.
850   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
851 
852   // Get the type for the builtin.
853   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
854   const llvm::FunctionType *Ty =
855     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
856 
857   // FIXME: This has a serious problem with code like this:
858   //  void abs() {}
859   //    ... __builtin_abs(x);
860   // The two versions of abs will collide.  The fix is for the builtin to win,
861   // and for the existing one to be turned into a constantexpr cast of the
862   // builtin.  In the case where the existing one is a static function, it
863   // should just be renamed.
864   if (llvm::Function *Existing = getModule().getFunction(Name)) {
865     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
866       return FunctionSlot = Existing;
867     assert(Existing == 0 && "FIXME: Name collision");
868   }
869 
870   // FIXME: param attributes for sext/zext etc.
871   return FunctionSlot =
872     llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
873                            &getModule());
874 }
875 
876 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
877                                             unsigned NumTys) {
878   return llvm::Intrinsic::getDeclaration(&getModule(),
879                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
880 }
881 
882 llvm::Function *CodeGenModule::getMemCpyFn() {
883   if (MemCpyFn) return MemCpyFn;
884   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
885   return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
886 }
887 
888 llvm::Function *CodeGenModule::getMemMoveFn() {
889   if (MemMoveFn) return MemMoveFn;
890   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
891   return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
892 }
893 
894 llvm::Function *CodeGenModule::getMemSetFn() {
895   if (MemSetFn) return MemSetFn;
896   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
897   return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
898 }
899 
900 static void appendFieldAndPadding(CodeGenModule &CGM,
901                                   std::vector<llvm::Constant*>& Fields,
902                                   FieldDecl *FieldD, FieldDecl *NextFieldD,
903                                   llvm::Constant* Field,
904                                   RecordDecl* RD, const llvm::StructType *STy)
905 {
906   // Append the field.
907   Fields.push_back(Field);
908 
909   int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
910 
911   int NextStructFieldNo;
912   if (!NextFieldD) {
913     NextStructFieldNo = STy->getNumElements();
914   } else {
915     NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
916   }
917 
918   // Append padding
919   for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
920     llvm::Constant *C =
921       llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
922 
923     Fields.push_back(C);
924   }
925 }
926 
927 // We still need to work out the details of handling UTF-16.
928 // See: <rdr://2996215>
929 llvm::Constant *CodeGenModule::
930 GetAddrOfConstantCFString(const std::string &str) {
931   llvm::StringMapEntry<llvm::Constant *> &Entry =
932     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
933 
934   if (Entry.getValue())
935     return Entry.getValue();
936 
937   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
938   llvm::Constant *Zeros[] = { Zero, Zero };
939 
940   if (!CFConstantStringClassRef) {
941     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
942     Ty = llvm::ArrayType::get(Ty, 0);
943 
944     // FIXME: This is fairly broken if
945     // __CFConstantStringClassReference is already defined, in that it
946     // will get renamed and the user will most likely see an opaque
947     // error message. This is a general issue with relying on
948     // particular names.
949     llvm::GlobalVariable *GV =
950       new llvm::GlobalVariable(Ty, false,
951                                llvm::GlobalVariable::ExternalLinkage, 0,
952                                "__CFConstantStringClassReference",
953                                &getModule());
954 
955     // Decay array -> ptr
956     CFConstantStringClassRef =
957       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
958   }
959 
960   QualType CFTy = getContext().getCFConstantStringType();
961   RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
962 
963   const llvm::StructType *STy =
964     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
965 
966   std::vector<llvm::Constant*> Fields;
967   RecordDecl::field_iterator Field = CFRD->field_begin();
968 
969   // Class pointer.
970   FieldDecl *CurField = *Field++;
971   FieldDecl *NextField = *Field++;
972   appendFieldAndPadding(*this, Fields, CurField, NextField,
973                         CFConstantStringClassRef, CFRD, STy);
974 
975   // Flags.
976   CurField = NextField;
977   NextField = *Field++;
978   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
979   appendFieldAndPadding(*this, Fields, CurField, NextField,
980                         llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
981 
982   // String pointer.
983   CurField = NextField;
984   NextField = *Field++;
985   llvm::Constant *C = llvm::ConstantArray::get(str);
986   C = new llvm::GlobalVariable(C->getType(), true,
987                                llvm::GlobalValue::InternalLinkage,
988                                C, ".str", &getModule());
989   appendFieldAndPadding(*this, Fields, CurField, NextField,
990                         llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
991                         CFRD, STy);
992 
993   // String length.
994   CurField = NextField;
995   NextField = 0;
996   Ty = getTypes().ConvertType(getContext().LongTy);
997   appendFieldAndPadding(*this, Fields, CurField, NextField,
998                         llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
999 
1000   // The struct.
1001   C = llvm::ConstantStruct::get(STy, Fields);
1002   llvm::GlobalVariable *GV =
1003     new llvm::GlobalVariable(C->getType(), true,
1004                              llvm::GlobalVariable::InternalLinkage,
1005                              C, "", &getModule());
1006 
1007   GV->setSection("__DATA,__cfstring");
1008   Entry.setValue(GV);
1009 
1010   return GV;
1011 }
1012 
1013 /// GetStringForStringLiteral - Return the appropriate bytes for a
1014 /// string literal, properly padded to match the literal type.
1015 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1016   if (E->isWide()) {
1017     ErrorUnsupported(E, "wide string");
1018     return "FIXME";
1019   }
1020 
1021   const char *StrData = E->getStrData();
1022   unsigned Len = E->getByteLength();
1023 
1024   const ConstantArrayType *CAT =
1025     getContext().getAsConstantArrayType(E->getType());
1026   assert(CAT && "String isn't pointer or array!");
1027 
1028   // Resize the string to the right size
1029   // FIXME: What about wchar_t strings?
1030   std::string Str(StrData, StrData+Len);
1031   uint64_t RealLen = CAT->getSize().getZExtValue();
1032   Str.resize(RealLen, '\0');
1033 
1034   return Str;
1035 }
1036 
1037 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1038 /// constant array for the given string literal.
1039 llvm::Constant *
1040 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1041   // FIXME: This can be more efficient.
1042   return GetAddrOfConstantString(GetStringForStringLiteral(S));
1043 }
1044 
1045 /// GenerateWritableString -- Creates storage for a string literal.
1046 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1047                                              bool constant,
1048                                              CodeGenModule &CGM,
1049                                              const char *GlobalName) {
1050   // Create Constant for this string literal. Don't add a '\0'.
1051   llvm::Constant *C = llvm::ConstantArray::get(str, false);
1052 
1053   // Create a global variable for this string
1054   C = new llvm::GlobalVariable(C->getType(), constant,
1055                                llvm::GlobalValue::InternalLinkage,
1056                                C,
1057                                GlobalName ? GlobalName : ".str",
1058                                &CGM.getModule());
1059 
1060   return C;
1061 }
1062 
1063 /// GetAddrOfConstantString - Returns a pointer to a character array
1064 /// containing the literal. This contents are exactly that of the
1065 /// given string, i.e. it will not be null terminated automatically;
1066 /// see GetAddrOfConstantCString. Note that whether the result is
1067 /// actually a pointer to an LLVM constant depends on
1068 /// Feature.WriteableStrings.
1069 ///
1070 /// The result has pointer to array type.
1071 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1072                                                        const char *GlobalName) {
1073   // Don't share any string literals if writable-strings is turned on.
1074   if (Features.WritableStrings)
1075     return GenerateStringLiteral(str, false, *this, GlobalName);
1076 
1077   llvm::StringMapEntry<llvm::Constant *> &Entry =
1078   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1079 
1080   if (Entry.getValue())
1081       return Entry.getValue();
1082 
1083   // Create a global variable for this.
1084   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1085   Entry.setValue(C);
1086   return C;
1087 }
1088 
1089 /// GetAddrOfConstantCString - Returns a pointer to a character
1090 /// array containing the literal and a terminating '\-'
1091 /// character. The result has pointer to array type.
1092 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1093                                                         const char *GlobalName){
1094   return GetAddrOfConstantString(str + '\0', GlobalName);
1095 }
1096 
1097 /// EmitObjCPropertyImplementations - Emit information for synthesized
1098 /// properties for an implementation.
1099 void CodeGenModule::EmitObjCPropertyImplementations(const
1100                                                     ObjCImplementationDecl *D) {
1101   for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1102          e = D->propimpl_end(); i != e; ++i) {
1103     ObjCPropertyImplDecl *PID = *i;
1104 
1105     // Dynamic is just for type-checking.
1106     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1107       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1108 
1109       // Determine which methods need to be implemented, some may have
1110       // been overridden. Note that ::isSynthesized is not the method
1111       // we want, that just indicates if the decl came from a
1112       // property. What we want to know is if the method is defined in
1113       // this implementation.
1114       if (!D->getInstanceMethod(PD->getGetterName()))
1115         CodeGenFunction(*this).GenerateObjCGetter(
1116                                  const_cast<ObjCImplementationDecl *>(D), PID);
1117       if (!PD->isReadOnly() &&
1118           !D->getInstanceMethod(PD->getSetterName()))
1119         CodeGenFunction(*this).GenerateObjCSetter(
1120                                  const_cast<ObjCImplementationDecl *>(D), PID);
1121     }
1122   }
1123 }
1124 
1125 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1126 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1127   // If an error has occurred, stop code generation, but continue
1128   // parsing and semantic analysis (to ensure all warnings and errors
1129   // are emitted).
1130   if (Diags.hasErrorOccurred())
1131     return;
1132 
1133   switch (D->getKind()) {
1134   case Decl::Function:
1135   case Decl::Var:
1136     EmitGlobal(cast<ValueDecl>(D));
1137     break;
1138 
1139   case Decl::Namespace:
1140     ErrorUnsupported(D, "namespace");
1141     break;
1142 
1143     // Objective-C Decls
1144 
1145     // Forward declarations, no (immediate) code generation.
1146   case Decl::ObjCClass:
1147   case Decl::ObjCCategory:
1148   case Decl::ObjCForwardProtocol:
1149   case Decl::ObjCInterface:
1150     break;
1151 
1152   case Decl::ObjCProtocol:
1153     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1154     break;
1155 
1156   case Decl::ObjCCategoryImpl:
1157     // Categories have properties but don't support synthesize so we
1158     // can ignore them here.
1159 
1160     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1161     break;
1162 
1163   case Decl::ObjCImplementation: {
1164     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1165     EmitObjCPropertyImplementations(OMD);
1166     Runtime->GenerateClass(OMD);
1167     break;
1168   }
1169   case Decl::ObjCMethod: {
1170     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1171     // If this is not a prototype, emit the body.
1172     if (OMD->getBody())
1173       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1174     break;
1175   }
1176   case Decl::ObjCCompatibleAlias:
1177     // compatibility-alias is a directive and has no code gen.
1178     break;
1179 
1180   case Decl::LinkageSpec: {
1181     LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1182     if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
1183       ErrorUnsupported(LSD, "linkage spec");
1184     // FIXME: implement C++ linkage, C linkage works mostly by C
1185     // language reuse already.
1186     break;
1187   }
1188 
1189   case Decl::FileScopeAsm: {
1190     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1191     std::string AsmString(AD->getAsmString()->getStrData(),
1192                           AD->getAsmString()->getByteLength());
1193 
1194     const std::string &S = getModule().getModuleInlineAsm();
1195     if (S.empty())
1196       getModule().setModuleInlineAsm(AsmString);
1197     else
1198       getModule().setModuleInlineAsm(S + '\n' + AsmString);
1199     break;
1200   }
1201 
1202   default:
1203     // Make sure we handled everything we should, every other kind is
1204     // a non-top-level decl.  FIXME: Would be nice to have an
1205     // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1206     // that easily.
1207     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1208   }
1209 }
1210