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