xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 7fab578b0dae4ea8c30e611bcdf2222e287aec90)
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 "CodeGenModule.h"
15 #include "CodeGenFunction.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/Basic/Diagnostic.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Intrinsics.h"
26 #include <algorithm>
27 using namespace clang;
28 using namespace CodeGen;
29 
30 
31 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
32                              llvm::Module &M, const llvm::TargetData &TD,
33                              Diagnostic &diags)
34   : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
35     Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
36   //TODO: Make this selectable at runtime
37   Runtime = CreateObjCRuntime(M,
38       getTypes().ConvertType(getContext().IntTy),
39       getTypes().ConvertType(getContext().LongTy));
40 }
41 
42 CodeGenModule::~CodeGenModule() {
43   llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
44   if (ObjCInitFunction)
45     AddGlobalCtor(ObjCInitFunction);
46   EmitGlobalCtors();
47   EmitAnnotations();
48   delete Runtime;
49 }
50 
51 /// WarnUnsupported - Print out a warning that codegen doesn't support the
52 /// specified stmt yet.
53 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
54   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
55                                                "cannot codegen this %0 yet");
56   SourceRange Range = S->getSourceRange();
57   std::string Msg = Type;
58   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
59                     &Msg, 1, &Range, 1);
60 }
61 
62 /// WarnUnsupported - Print out a warning that codegen doesn't support the
63 /// specified decl yet.
64 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
65   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
66                                                "cannot codegen this %0 yet");
67   std::string Msg = Type;
68   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
69                     &Msg, 1);
70 }
71 
72 /// AddGlobalCtor - Add a function to the list that will be called before
73 /// main() runs.
74 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
75   // TODO: Type coercion of void()* types.
76   GlobalCtors.push_back(Ctor);
77 }
78 
79 /// EmitGlobalCtors - Generates the array of contsturctor functions to be
80 /// called on module load, if any have been registered with AddGlobalCtor.
81 void CodeGenModule::EmitGlobalCtors() {
82   if (GlobalCtors.empty()) return;
83 
84   // Get the type of @llvm.global_ctors
85   std::vector<const llvm::Type*> CtorFields;
86   CtorFields.push_back(llvm::IntegerType::get(32));
87   // Constructor function type
88   std::vector<const llvm::Type*> VoidArgs;
89   llvm::FunctionType* CtorFuncTy =
90     llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
91 
92   // i32, function type pair
93   const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
94   llvm::StructType* CtorStructTy =
95   llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
96   // Array of fields
97   llvm::ArrayType* GlobalCtorsTy =
98     llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
99 
100   // Define the global variable
101   llvm::GlobalVariable *GlobalCtorsVal =
102     new llvm::GlobalVariable(GlobalCtorsTy, false,
103                              llvm::GlobalValue::AppendingLinkage,
104                              (llvm::Constant*)0, "llvm.global_ctors",
105                              &TheModule);
106 
107   // Populate the array
108   std::vector<llvm::Constant*> CtorValues;
109   llvm::Constant *MagicNumber =
110     llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
111   std::vector<llvm::Constant*> StructValues;
112   for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
113        E = GlobalCtors.end(); I != E; ++I) {
114     StructValues.clear();
115     StructValues.push_back(MagicNumber);
116     StructValues.push_back(*I);
117 
118     CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
119   }
120 
121   GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
122                                                           CtorValues));
123 }
124 
125 
126 
127 void CodeGenModule::EmitAnnotations() {
128   if (Annotations.empty())
129     return;
130 
131   // Create a new global variable for the ConstantStruct in the Module.
132   llvm::Constant *Array =
133   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
134                                                 Annotations.size()),
135                            Annotations);
136   llvm::GlobalValue *gv =
137   new llvm::GlobalVariable(Array->getType(), false,
138                            llvm::GlobalValue::AppendingLinkage, Array,
139                            "llvm.global.annotations", &TheModule);
140   gv->setSection("llvm.metadata");
141 }
142 
143 /// ReplaceMapValuesWith - This is a really slow and bad function that
144 /// searches for any entries in GlobalDeclMap that point to OldVal, changing
145 /// them to point to NewVal.  This is badbadbad, FIXME!
146 void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
147                                          llvm::Constant *NewVal) {
148   for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
149        I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
150     if (I->second == OldVal) I->second = NewVal;
151 }
152 
153 
154 llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
155                                                      bool isDefinition) {
156   // See if it is already in the map.  If so, just return it.
157   llvm::Constant *&Entry = GlobalDeclMap[D];
158   if (Entry) return Entry;
159 
160   const llvm::Type *Ty = getTypes().ConvertType(D->getType());
161 
162   // Check to see if the function already exists.
163   llvm::Function *F = getModule().getFunction(D->getName());
164   const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
165 
166   // If it doesn't already exist, just create and return an entry.
167   if (F == 0) {
168     // FIXME: param attributes for sext/zext etc.
169     F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, D->getName(),
170                            &getModule());
171 
172     // Set the appropriate calling convention for the Function.
173     if (D->getAttr<FastCallAttr>())
174       F->setCallingConv(llvm::CallingConv::Fast);
175     return Entry = F;
176   }
177 
178   // If the pointer type matches, just return it.
179   llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
180   if (PFTy == F->getType()) return Entry = F;
181 
182   // If this isn't a definition, just return it casted to the right type.
183   if (!isDefinition)
184     return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
185 
186   // Otherwise, we have a definition after a prototype with the wrong type.
187   // F is the Function* for the one with the wrong type, we must make a new
188   // Function* and update everything that used F (a declaration) with the new
189   // Function* (which will be a definition).
190   //
191   // This happens if there is a prototype for a function (e.g. "int f()") and
192   // then a definition of a different type (e.g. "int f(int x)").  Start by
193   // making a new function of the correct type, RAUW, then steal the name.
194   llvm::Function *NewFn = llvm::Function::Create(FTy,
195                                              llvm::Function::ExternalLinkage,
196                                              "", &getModule());
197   NewFn->takeName(F);
198 
199   // Replace uses of F with the Function we will endow with a body.
200   llvm::Constant *NewPtrForOldDecl =
201     llvm::ConstantExpr::getBitCast(NewFn, F->getType());
202   F->replaceAllUsesWith(NewPtrForOldDecl);
203 
204   // FIXME: Update the globaldeclmap for the previous decl of this name.  We
205   // really want a way to walk all of these, but we don't have it yet.  This
206   // is incredibly slow!
207   ReplaceMapValuesWith(F, NewPtrForOldDecl);
208 
209   // Ok, delete the old function now, which is dead.
210   assert(F->isDeclaration() && "Shouldn't replace non-declaration");
211   F->eraseFromParent();
212 
213   // Return the new function which has the right type.
214   return Entry = NewFn;
215 }
216 
217 static bool IsZeroElementArray(const llvm::Type *Ty) {
218   if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
219     return ATy->getNumElements() == 0;
220   return false;
221 }
222 
223 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
224                                                   bool isDefinition) {
225   assert(D->hasGlobalStorage() && "Not a global variable");
226 
227   // See if it is already in the map.
228   llvm::Constant *&Entry = GlobalDeclMap[D];
229   if (Entry) return Entry;
230 
231   QualType ASTTy = D->getType();
232   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
233 
234   // Check to see if the global already exists.
235   llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
236 
237   // If it doesn't already exist, just create and return an entry.
238   if (GV == 0) {
239     return Entry = new llvm::GlobalVariable(Ty, false,
240                                             llvm::GlobalValue::ExternalLinkage,
241                                             0, D->getName(), &getModule(), 0,
242                                             ASTTy.getAddressSpace());
243   }
244 
245   // If the pointer type matches, just return it.
246   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
247   if (PTy == GV->getType()) return Entry = GV;
248 
249   // If this isn't a definition, just return it casted to the right type.
250   if (!isDefinition)
251     return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
252 
253 
254   // Otherwise, we have a definition after a prototype with the wrong type.
255   // GV is the GlobalVariable* for the one with the wrong type, we must make a
256   /// new GlobalVariable* and update everything that used GV (a declaration)
257   // with the new GlobalVariable* (which will be a definition).
258   //
259   // This happens if there is a prototype for a global (e.g. "extern int x[];")
260   // and then a definition of a different type (e.g. "int x[10];").  Start by
261   // making a new global of the correct type, RAUW, then steal the name.
262   llvm::GlobalVariable *NewGV =
263     new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
264                              0, D->getName(), &getModule(), 0,
265                              ASTTy.getAddressSpace());
266   NewGV->takeName(GV);
267 
268   // Replace uses of GV with the globalvalue we will endow with a body.
269   llvm::Constant *NewPtrForOldDecl =
270     llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
271   GV->replaceAllUsesWith(NewPtrForOldDecl);
272 
273   // FIXME: Update the globaldeclmap for the previous decl of this name.  We
274   // really want a way to walk all of these, but we don't have it yet.  This
275   // is incredibly slow!
276   ReplaceMapValuesWith(GV, NewPtrForOldDecl);
277 
278   // Verify that GV was a declaration or something like x[] which turns into
279   // [0 x type].
280   assert((GV->isDeclaration() ||
281           IsZeroElementArray(GV->getType()->getElementType())) &&
282          "Shouldn't replace non-declaration");
283 
284   // Ok, delete the old global now, which is dead.
285   GV->eraseFromParent();
286 
287   // Return the new global which has the right type.
288   return Entry = NewGV;
289 }
290 
291 
292 void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
293   // If this is not a prototype, emit the body.
294   if (OMD->getBody())
295     CodeGenFunction(*this).GenerateObjCMethod(OMD);
296 }
297 
298 void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
299   // If this is not a prototype, emit the body.
300   if (FD->getBody())
301     CodeGenFunction(*this).GenerateCode(FD);
302 }
303 
304 llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
305   return EmitConstantExpr(Expr);
306 }
307 
308 void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
309   // If this is just a forward declaration of the variable, don't emit it now,
310   // allow it to be emitted lazily on its first use.
311   if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
312     return;
313 
314   // Get the global, forcing it to be a direct reference.
315   llvm::GlobalVariable *GV =
316     cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
317 
318   // Convert the initializer, or use zero if appropriate.
319   llvm::Constant *Init = 0;
320   if (D->getInit() == 0) {
321     Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
322   } else if (D->getType()->isIntegerType()) {
323     llvm::APSInt Value(static_cast<uint32_t>(
324       getContext().getTypeSize(D->getInit()->getType())));
325     if (D->getInit()->isIntegerConstantExpr(Value, Context))
326       Init = llvm::ConstantInt::get(Value);
327   }
328 
329   if (!Init)
330     Init = EmitGlobalInit(D->getInit());
331 
332   assert(GV->getType()->getElementType() == Init->getType() &&
333          "Initializer codegen type mismatch!");
334   GV->setInitializer(Init);
335 
336   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
337     GV->setVisibility(attr->getVisibility());
338   // FIXME: else handle -fvisibility
339 
340   // Set the llvm linkage type as appropriate.
341   if (D->getAttr<DLLImportAttr>())
342     GV->setLinkage(llvm::Function::DLLImportLinkage);
343   else if (D->getAttr<DLLExportAttr>())
344     GV->setLinkage(llvm::Function::DLLExportLinkage);
345   else if (D->getAttr<WeakAttr>()) {
346     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
347 
348   } else {
349     // FIXME: This isn't right.  This should handle common linkage and other
350     // stuff.
351     switch (D->getStorageClass()) {
352     case VarDecl::Auto:
353     case VarDecl::Register:
354       assert(0 && "Can't have auto or register globals");
355     case VarDecl::None:
356       if (!D->getInit())
357         GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
358       break;
359     case VarDecl::Extern:
360     case VarDecl::PrivateExtern:
361       // todo: common
362       break;
363     case VarDecl::Static:
364       GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
365       break;
366     }
367   }
368 }
369 
370 /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
371 /// declarator chain.
372 void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
373   for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
374     if (D->isFileVarDecl())
375       EmitGlobalVar(D);
376 }
377 
378 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
379   // Make sure that this type is translated.
380   Types.UpdateCompletedType(TD);
381 }
382 
383 
384 /// getBuiltinLibFunction
385 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
386   if (BuiltinID > BuiltinFunctions.size())
387     BuiltinFunctions.resize(BuiltinID);
388 
389   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
390   // a slot for it.
391   assert(BuiltinID && "Invalid Builtin ID");
392   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
393   if (FunctionSlot)
394     return FunctionSlot;
395 
396   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
397 
398   // Get the name, skip over the __builtin_ prefix.
399   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
400 
401   // Get the type for the builtin.
402   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
403   const llvm::FunctionType *Ty =
404     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
405 
406   // FIXME: This has a serious problem with code like this:
407   //  void abs() {}
408   //    ... __builtin_abs(x);
409   // The two versions of abs will collide.  The fix is for the builtin to win,
410   // and for the existing one to be turned into a constantexpr cast of the
411   // builtin.  In the case where the existing one is a static function, it
412   // should just be renamed.
413   if (llvm::Function *Existing = getModule().getFunction(Name)) {
414     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
415       return FunctionSlot = Existing;
416     assert(Existing == 0 && "FIXME: Name collision");
417   }
418 
419   // FIXME: param attributes for sext/zext etc.
420   return FunctionSlot = llvm::Function::Create(Ty, llvm::Function::ExternalLinkage,
421                                            Name, &getModule());
422 }
423 
424 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
425                                             unsigned NumTys) {
426   return llvm::Intrinsic::getDeclaration(&getModule(),
427                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
428 }
429 
430 llvm::Function *CodeGenModule::getMemCpyFn() {
431   if (MemCpyFn) return MemCpyFn;
432   llvm::Intrinsic::ID IID;
433   switch (Context.Target.getPointerWidth(0)) {
434   default: assert(0 && "Unknown ptr width");
435   case 32: IID = llvm::Intrinsic::memcpy_i32; break;
436   case 64: IID = llvm::Intrinsic::memcpy_i64; break;
437   }
438   return MemCpyFn = getIntrinsic(IID);
439 }
440 
441 llvm::Function *CodeGenModule::getMemSetFn() {
442   if (MemSetFn) return MemSetFn;
443   llvm::Intrinsic::ID IID;
444   switch (Context.Target.getPointerWidth(0)) {
445   default: assert(0 && "Unknown ptr width");
446   case 32: IID = llvm::Intrinsic::memset_i32; break;
447   case 64: IID = llvm::Intrinsic::memset_i64; break;
448   }
449   return MemSetFn = getIntrinsic(IID);
450 }
451 
452 llvm::Constant *CodeGenModule::
453 GetAddrOfConstantCFString(const std::string &str) {
454   llvm::StringMapEntry<llvm::Constant *> &Entry =
455     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
456 
457   if (Entry.getValue())
458     return Entry.getValue();
459 
460   std::vector<llvm::Constant*> Fields;
461 
462   if (!CFConstantStringClassRef) {
463     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
464     Ty = llvm::ArrayType::get(Ty, 0);
465 
466     CFConstantStringClassRef =
467       new llvm::GlobalVariable(Ty, false,
468                                llvm::GlobalVariable::ExternalLinkage, 0,
469                                "__CFConstantStringClassReference",
470                                &getModule());
471   }
472 
473   // Class pointer.
474   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
475   llvm::Constant *Zeros[] = { Zero, Zero };
476   llvm::Constant *C =
477     llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
478   Fields.push_back(C);
479 
480   // Flags.
481   const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
482   Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
483 
484   // String pointer.
485   C = llvm::ConstantArray::get(str);
486   C = new llvm::GlobalVariable(C->getType(), true,
487                                llvm::GlobalValue::InternalLinkage,
488                                C, ".str", &getModule());
489 
490   C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
491   Fields.push_back(C);
492 
493   // String length.
494   Ty = getTypes().ConvertType(getContext().LongTy);
495   Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
496 
497   // The struct.
498   Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
499   C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
500   llvm::GlobalVariable *GV =
501     new llvm::GlobalVariable(C->getType(), true,
502                              llvm::GlobalVariable::InternalLinkage,
503                              C, "", &getModule());
504   GV->setSection("__DATA,__cfstring");
505   Entry.setValue(GV);
506   return GV;
507 }
508 
509 /// GenerateWritableString -- Creates storage for a string literal.
510 static llvm::Constant *GenerateStringLiteral(const std::string &str,
511                                              bool constant,
512                                              CodeGenModule &CGM) {
513   // Create Constant for this string literal
514   llvm::Constant *C=llvm::ConstantArray::get(str);
515 
516   // Create a global variable for this string
517   C = new llvm::GlobalVariable(C->getType(), constant,
518                                llvm::GlobalValue::InternalLinkage,
519                                C, ".str", &CGM.getModule());
520   return C;
521 }
522 
523 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
524 /// array containing the literal.  The result is pointer to array type.
525 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
526   // Don't share any string literals if writable-strings is turned on.
527   if (Features.WritableStrings)
528     return GenerateStringLiteral(str, false, *this);
529 
530   llvm::StringMapEntry<llvm::Constant *> &Entry =
531   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
532 
533   if (Entry.getValue())
534       return Entry.getValue();
535 
536   // Create a global variable for this.
537   llvm::Constant *C = GenerateStringLiteral(str, true, *this);
538   Entry.setValue(C);
539   return C;
540 }
541