+/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
+/// this is a declaration, otherwise it is a definition.
+static GlobalVariable *
+ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
+ bool isConstantGlobal, const Type *Ty,
+ Constant *Initializer) {
+ if (isa<FunctionType>(Ty))
+ ThrowException("Cannot declare global vars of function type!");
+
+ const PointerType *PTy = PointerType::get(Ty);
+
+ std::string Name;
+ if (NameStr) {
+ Name = NameStr; // Copy string
+ free(NameStr); // Free old string
+ }
+
+ // See if this global value was forward referenced. If so, recycle the
+ // object.
+ ValID ID;
+ if (!Name.empty()) {
+ ID = ValID::create((char*)Name.c_str());
+ } else {
+ ID = ValID::create((int)CurModule.Values[PTy].size());
+ }
+
+ if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
+ // Move the global to the end of the list, from whereever it was
+ // previously inserted.
+ GlobalVariable *GV = cast<GlobalVariable>(FWGV);
+ CurModule.CurrentModule->getGlobalList().remove(GV);
+ CurModule.CurrentModule->getGlobalList().push_back(GV);
+ GV->setInitializer(Initializer);
+ GV->setLinkage(Linkage);
+ GV->setConstant(isConstantGlobal);
+ InsertValue(GV, CurModule.Values);
+ return GV;
+ }
+
+ // If this global has a name, check to see if there is already a definition
+ // of this global in the module. If so, merge as appropriate. Note that
+ // this is really just a hack around problems in the CFE. :(
+ if (!Name.empty()) {
+ // We are a simple redefinition of a value, check to see if it is defined
+ // the same as the old one.
+ if (GlobalVariable *EGV =
+ CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
+ // We are allowed to redefine a global variable in two circumstances:
+ // 1. If at least one of the globals is uninitialized or
+ // 2. If both initializers have the same value.
+ //
+ if (!EGV->hasInitializer() || !Initializer ||
+ EGV->getInitializer() == Initializer) {
+
+ // Make sure the existing global version gets the initializer! Make
+ // sure that it also gets marked const if the new version is.
+ if (Initializer && !EGV->hasInitializer())
+ EGV->setInitializer(Initializer);
+ if (isConstantGlobal)
+ EGV->setConstant(true);
+ EGV->setLinkage(Linkage);
+ return EGV;
+ }
+
+ ThrowException("Redefinition of global variable named '" + Name +
+ "' in the '" + Ty->getDescription() + "' type plane!");
+ }
+ }