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