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